# [R] Sorting rows in a matrix based on vector of indecies

David Winsemius dwinsemius at comcast.net
Sat Feb 21 00:45:34 CET 2009

```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]

--
David Winsemius

On Feb 20, 2009, at 6:16 PM, Esmail Bonakdarian wrote:

> Hello
>
> I have a matrix of size rows x cols.
> I also have a vector  of size rows.
>
> The vector contains index values that corresponds to rows in the
> matrix.
>
> I would like to re-arrange/sort the contents of the matrix according
> to the entries in the vector. Can this be done efficiently in R and
> possibly in place? Or would it be better to allocate another whole
> matrix?
>
> Simple example:
>
> matrix:
> ffffff
> aaaaaa
> zzzzzz
> bbbbbb
>
>
> vector:
> 2, 4, 1, 3
>
> "new" matrix:
> aaaaaa
> bbbbbb
> ffffff
> zzzzzz
>
>
> I suppose I could allocate another matrix and loop through the vector
> of indecies placing entries into the new matrix. Do I have to worry
> about deallocating the memory space of the first matrix or will it
> automagically go away if I assign the new matrix to the old matrix
> identifier (assuming nothing else is pointing at it)?
>
> Thanks,
> Esmail
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help