Skip to content

Sorting each column of a matrix independently

3 messages · Desmond Lim, Ken Beath, Todd A. Johnson

#
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
#
This question should be directed to R-Help

Anyway, sorted <- apply(unsorted,2,sort) should do it.

Ken
On 14/10/2010, at 7:06 PM, Desmond Lim wrote:

            
#
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: