Suppose that I have an n
row, m
column matrix A
, and I want to reorder every column in m
according to the sorting of some specific row.
For instance, if I take order(A[,k])
, that gives me the numeric or alphabetical order of elements in column k
. I now want to sort every column in matrix A
according to those rankings, so that elements 1...n
in every row are ordered to correspond to elements 1...n
(by rank) in column k
. Is there a simple way to do this without looping over all columns?
Just use:
A[order(A[,k]),]
For example:
set.seed(21)
A <- matrix(rnorm(50),10,5)
A[order(A[,1]),]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With