[R] order matrix by column position

Gabor Grothendieck ggrothendieck at gmail.com
Thu Dec 9 23:34:19 CET 2010


On Thu, Dec 9, 2010 at 5:24 PM, Folkes, Michael
<Michael.Folkes at dfo-mpo.gc.ca> wrote:
> Hello all,
> I'm trying to grasp a way to order a matrix by giving order() only a vector of the columns it can look to for sorting.
> The approach has to be generic such that I can feed order() a vector of variable length (ie varying # of columns to sort by).
>
>
> x<-rep(1,9)
> y<-c(1, 1, 2, 2, 2, 1, 2, 2, 2)
> z<-c(10, 11, 10, 13,  15,1000,1000, 1001,1002)
> results<-cbind(x,y,z)
>
> #pseudocode:
> # results[order(vector of column numbers),]
>
> # order desired:
> results[order(results[,1],results[,2],results[,3]),]

Try this:

ix <- 1:3
results[do.call(order, as.data.frame(results)[ix]), ]

as.data.frame can optionally be omitted if the results object is
already a data frame (in your example code its a matrix).

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list