[R] Order a matrix

William Dunlap wdunlap at tibco.com
Tue May 24 21:22:21 CEST 2011


Try using do.call("order", listOfColumnsToSortBy), as in
  cols <- c(1,3,4)
  x[do.call("order", as.data.frame(x[,cols])), ]

To be really safe you should remove the names from the data.frame
produced by as.data.frame (in case they match the argument names
of order), as in
  x[do.call("order", unname(as.list(as.data.frame(x[,cols])))),]
or
  x[do.call("order", unname(split(x[,cols], col(x[,cols])))), ]

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Lisa
> Sent: Tuesday, May 24, 2011 12:00 PM
> To: r-help at r-project.org
> Subject: [R] Order a matrix
> 
> Dear all,
> 
> I just want to order a matrix using several columns in a matrix. For
> example:
> 
> x <- matrix(sample(c(1:5), 60, replace = T), 10, 6).
> 
> If I order the matrix by the first two columns, I will do it 
> like this:
>  
> x[order(x[, 1], x[, 2]), ]. 
> 
> But when I repeat this work many times and the columns will 
> change each time
> in a simulation study, how can I assign the arguments of order()? For
> example, in the first iteration, the columns needing to order 
> is the first
> two columns, in the second iteration, the columns needing to 
> order is the
> first, second, and fourth column? ....
> 
> I would appreciate any help on this question. Thanks a lot.
> 
> Lisa
> 
> 
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/Order-a-matrix-tp3547923p3547923.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list