Skip to content
Prev 171246 / 398503 Next

Sorting rows in a matrix based on vector of indecies

Since you do not offer reproducible code, I must guess that you were  
thinking of this as a matrix with 6 instances of "a" across the top  
row. See if this helps:

 > mtx<-matrix( rep(letters[1:4], 6), nrow=4)
 > mtx
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a"  "a"  "a"  "a"  "a"  "a"
[2,] "b"  "b"  "b"  "b"  "b"  "b"
[3,] "c"  "c"  "c"  "c"  "c"  "c"
[4,] "d"  "d"  "d"  "d"  "d"  "d"

 > mtx[c(2, 4, 1, 3), ]

      [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "b"  "b"  "b"  "b"  "b"  "b"
[2,] "d"  "d"  "d"  "d"  "d"  "d"
[3,] "a"  "a"  "a"  "a"  "a"  "a"
[4,] "c"  "c"  "c"  "c"  "c"  "c"

You can do with that result whatever you want:

assign it,   m2 <- mtx[c(2, 4, 1, 3), ]

mtx <- mtx[c(2, 4, 1, 3), ]

(unless you assign back to itself you will not have altered mtx.)

subset it, by element index mtx[c(2, 4, 1, 3), ][20]

            by row m3 <- mtx[c(2, 4, 1, 3), ][4, ]

            or by column. mtx[c(2, 4, 1, 3), ][ , 6]