On Sep 1, 2010, at 11:18 AM, <murali.me...@avivainvestors.com> wrote:

Hi folks,

I want to sort a matrix row-by-row and create a new matrix that contains the corresponding colnames of the original matrix.

E.g.

set.seed(123)
a <- matrix(rnorm(20), ncol=4); colnames(a) <- c("A","B","C","D")
a
              A          B          C          D
[1,] -0.56047565  1.7150650  1.2240818  1.7869131
[2,] -0.23017749  0.4609162  0.3598138  0.4978505
[3,]  1.55870831 -1.2650612  0.4007715 -1.9666172
[4,]  0.07050839 -0.6868529  0.1106827  0.7013559
[5,]  0.12928774 -0.4456620 -0.5558411 -0.4727914

I want to obtain a matrix that looks like this

> t( apply(a, 1, function(x) colnames(a)[order(x)]) )
     [,1] [,2] [,3] [,4]
[1,] "A"  "C"  "B"  "D"
[2,] "A"  "C"  "B"  "D"
[3,] "D"  "B"  "C"  "A"
[4,] "B"  "A"  "C"  "D"
[5,] "C"  "D"  "B"  "A"

(apply returns a transposed version.)

A C B D
A C B D
D B C A
B A C D
C D B A

How best to achieve this? I was able to do it for the max and min of each row by which.min, which.max, but for the entire thing, I'm stymied.


--
David Winsemius, MD
West Hartford, CT

______________________________________________
R-help@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.

Reply via email to