Skip to content

Sort matrix by column 1 ascending then by column 2 decending

4 messages · Paul Geeleher, Henrique Dallazuanna, Duncan Murdoch

#
I've got a matrix with 2 columns and n rows. I need to sort it first
by the values in column 1 ascending. Then for values which are the
same in column 1, sort by column 2 decending. For example:

2 .5
1 .3
1 .5
3 .2

Goes to:

1 .5
1 .3
2 .5
3 .2

This is easy to do in spreadsheet programs but I can't seem to work
out how to do it in R and haven't been able to find a solution
anywhere.


Thanks!

-Paul.
#
Nice. Works perfectly.
On Wed, May 27, 2009 at 2:03 PM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote:

  
    
#
On 5/27/2009 8:39 AM, Paul Geeleher wrote:
You've seen a few ways.  Here are some more:

1.  Use the fact that order() uses a stable sort algorithm, so just sort 
by the second column then the first:

x <- matrix(c(2,1,1,3,.5,.3,.5,.2), ncol=2)
x1 <- x[order(x[,2], decreasing=TRUE),]
x2 <- x1[order(x1[,1]),]
x2

2.  Use the fact that your values are numeric, so negatives sort in the 
reverse order of positives:

x[order(x[,1], -x[,2]),]

3.  If the values aren't known to be numeric, convert them to numeric 
before using them as sort keys:

x[order(xtfrm(x[,1]), -xtfrm(x[,2])),]

In any of these, watch out for NA handling.  My methods all put NA 
values last, but that might not be what you want.

Duncan Murdoch