Murali.Menon at avivainvestors.com
2010-Sep-01 15:18 UTC
[R] getting column names of row-by-row sorted matrix
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") > aA 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 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. Thanks, Murali
David Winsemius
2010-Sep-01 15:34 UTC
[R] getting column names of row-by-row sorted matrix
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
David Winsemius
2010-Sep-01 15:54 UTC
[R] getting column names of row-by-row sorted matrix
On Sep 1, 2010, at 11:34 AM, David Winsemius wrote:> > snipped > > 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.)That is over-broad. apply() only returns a "transposed" result of a matrix when the second argument is "1". It is (as I understand it anyway) supplying results for building another matrix in the default, for R, column-major order. If you start with rows uou gt columns. If your start with columns you get columns. And someday I will figure out how this generalizes to arrays. apply(mtx, 1, I) #transposes apply(mtx, 2, I) #does not "transpose" -- David Winsemius, MD West Hartford, CT