Skip to content
Prev 7523 / 15075 Next

Sorting each column of a matrix independently

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: