[R] getting column names of row-by-row sorted matrix
David Winsemius
dwinsemius at comcast.net
Wed Sep 1 17:34:07 CEST 2010
On Sep 1, 2010, at 11:18 AM, <Murali.Menon at 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
More information about the R-help
mailing list