[R] sort rows of matrix by rows of another matrix
Johnson, Eric A. (Seattle)
Eric.Johnson10 at va.gov
Fri Aug 1 00:05:54 CEST 2008
If you're not adverse to cbind-ing a1 and a2, you can use this:
a1a2 <- cbind(a1, a2)
a3 <- t(apply(a1a2, 1, function(x) x[order(x[1:ncol(a1)])+ncol(a1)]))
Eric
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Timothy W. Hilton
Sent: Thursday, July 31, 2008 2:19 PM
To: r-help at r-project.org
Subject: [R] sort rows of matrix by rows of another matrix
Hello all,
I am trying to sort rows of one matrix by rows of another. Given a1 and
a2:
------
> a1
[,1] [,2] [,3]
[1,] 7 6 8
[2,] 4 2 4
[3,] 4 7 2
[4,] 0 3 8
a1 <-
structure(c(7, 4, 4, 0, 6, 2, 7, 3, 8, 4, 2, 8), .Dim = c(4L, 3L))
> a2
[,1] [,2] [,3]
[1,] 101 102 103
[2,] 101 102 103
[3,] 101 102 103
[4,] 101 102 103
a2 <-
structure(c(101L, 101L, 101L, 101L, 102L, 102L, 102L, 102L, 103L,
103L, 103L, 103L), .Dim = c(4L, 3L))
------
I want to get a3:
> a3
[,1] [,2] [,3]
[1,] 102 101 103
[2,] 102 101 103
[3,] 103 101 102
[4,] 101 102 103
where the rows of a3 are the rows of a2 sorted according to the rows of
a1.
I can get the necessary sorting index:
> apply(a1, 1, order)
[,1] [,2] [,3] [,4]
[1,] 2 2 3 1
[2,] 1 1 1 2
[3,] 3 3 2 3
and I can get the rows of a1 sorted according to the rows of a1:
> t(apply(a1, 1, function(x) x[order(x)]))
[,1] [,2] [,3]
[1,] 6 7 8
[2,] 2 4 4
[3,] 2 4 7
[4,] 0 3 8
but I can't get the rows of a2 sorted according to the rows of a1...
Thanks,
Tim
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list