[R-SIG-Mac] Sorting each column of a matrix independently

Todd A. Johnson tjohnson at src.riken.jp
Thu Oct 14 10:51:43 CEST 2010


Hi Desmond,

Perhaps I'm not understanding something, but using sort on separate columns
looks too complicated to me...

According to help(sort), sort is for a vector or factor, and order is for
sorting dataframes (or matrices).

So, you should be able to do:

sorted <- unsorted[order(unsorted[,1], unsorted[,2]),]

Stick a minus sign in front of columns if you want decreasing order:

sorted <- unsorted[order(unsorted[,1], -unsorted[,2]),]

Would sort by the first column in increasing order and the second column by
descreasing order.

Change the order of the columns within the order() statement depending on
which columns have preference during the ordering.

Best wishes,

Todd 


On 10/14/10 5:06 PM, "Desmond Lim" <limwenpin at gmail.com> wrote:

> Hi,
> 
> I have this matrix
> 
> unsorted$A with 5 columns (all numeric).
> 
> Currently I'm sorting the columns like this:
> 
> sorted$A[,1] <- sort(unsorted$A[,1])
> sorted$A[,2] <- sort(unsorted$A[,2]) ...
> 
> I have tried doing
> 
> sorted$A <- unsorted$A[do.call(order, data.frame(unsorted$A)),] but it
> sorts the first column then the 2nd column which it ties to the 1st
> column, then the 3rd which is tied to the 2nd, etc. I need all the
> columns to be independently sorted.
> 
> Any help is appreciated.
> 
> Desmond
> 
> _______________________________________________
> R-SIG-Mac mailing list
> R-SIG-Mac at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-mac
>



More information about the R-SIG-Mac mailing list