[R] sorting a matrix by a different colnames order
jim holtman
jholtman at gmail.com
Wed Feb 7 15:16:02 CET 2007
> mx = matrix(rnorm(1:20),5,4)
> colnames(mx) = letters[1:4]
> rownames(mx) = letters[1:5]
> mx
a b c d
a -0.6264538 -0.8204684 1.5117812 -0.04493361
b 0.1836433 0.4874291 0.3898432 -0.01619026
c -0.8356286 0.7383247 -0.6212406 0.94383621
d 1.5952808 0.5757814 -2.2146999 0.82122120
e 0.3295078 -0.3053884 1.1249309 0.59390132
> (new.col.names = sample(letters[1:4]))
[1] "d" "b" "c" "a"
> mx[, new.col.names]
d b c a
a -0.04493361 -0.8204684 1.5117812 -0.6264538
b -0.01619026 0.4874291 0.3898432 0.1836433
c 0.94383621 0.7383247 -0.6212406 -0.8356286
d 0.82122120 0.5757814 -2.2146999 1.5952808
e 0.59390132 -0.3053884 1.1249309 0.3295078
>
On 2/7/07, portnoy at supereva.it <portnoy at supereva.it> wrote:
> Hi R users,
> I would like to know how to sort a matrix according a different order of
> colnames (or rownames) ,e.g.,
> mx = matrix(rnorm(1:20),5,4)
> colnames(mx) = letters[1:4]
> rownames(mx) = letters[1:5]
> mx
> a b c d
> a 0.02362598 -0.7033460 0.8106089 -1.03456219
> b -0.45021522 -1.5769522 0.1770634 0.27997249
> c 1.34732392 0.2956623 2.0027231 -0.85321627
> d 0.82314457 1.2698347 -0.5468151 0.05806375
> e -0.18668401 -0.4210383 0.6263465 -0.18889031
>
> (new.col.names = sample(letters[1:4]))
> [1] "a" "b" "d" "c"
>
> so the new matrix has to be ordered according the new.col.names,i.e.,
> a b d c
> a 0.02362598 -0.7033460 -1.03456219 0.8106089
> b -0.45021522 -1.5769522 0.27997249 0.1770634
> c 1.34732392 0.2956623 -0.85321627 2.0027231
> d 0.82314457 1.2698347 0.05806375 -0.5468151
> e -0.18668401 -0.4210383 -0.18889031 0.6263465
>
> Hope this is not a "basic question"
>
> Thank you for your help.
>
> Paolo
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?
More information about the R-help
mailing list