Order a matrix by multiple column in r

order function will help you out, try this:

df[order(-df[,1],-df[,2]),] 
  [,1] [,2]
b    7    0
c    5    0
a    3    0
e    1    0
f    0    9
d    0    8

The minus before df indicates that the order is decreasing. You will get the same result setting decreasing=TRUE.

df[order(df[,1],df[,2],decreasing=TRUE),]

The order function should do it.

df[order(df[,1],df[,2],decreasing=TRUE),]

To complete the main answer, here is a way to do it programmatically, without having to specify the columns by hand:

set.seed(2013) # preparing my example
mat <- matrix(sample.int(10,size = 30, replace = T), ncol = 3)
mat
      [,1] [,2] [,3]
 [1,]    5    1    6
 [2,]   10    3    1
 [3,]    8    8    1
 [4,]    8    9    9
 [5,]    3    7    3
 [6,]    8    8    5
 [7,]   10   10    2
 [8,]    8   10    7
 [9,]   10    1    9
[10,]    9    4    5

As a simple example, let say I want to use all the columns in their order of appearance to sort the rows of the matrix: (One could easily give a vector of indexes to the matrix)

mat[do.call(order, as.data.frame(mat)),]   #could be ..as.data.frame(mat[,index_vec])..
      [,1] [,2] [,3]
 [1,]    3    7    3
 [2,]    5    1    6
 [3,]    8    8    1
 [4,]    8    8    5
 [5,]    8    9    9
 [6,]    8   10    7
 [7,]    9    4    5
 [8,]   10    1    9
 [9,]   10    3    1
[10,]   10   10    2

Tags:

Sorting

Matrix

R