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

Esmail Bonakdarian esmail.js at gmail.com
Sat Feb 21 00:16:16 CET 2009


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




More information about the R-help mailing list