[R] sorting multiple columns of a matrix

William Dunlap wdunlap at tibco.com
Fri Sep 23 18:28:46 CEST 2011


Use do.call(func, listOfArgs) when you don't
know how many arguments will be passed to func.
E.g.,
  > x <- cbind(round(sin(1:10)), round(cos(1:10)), round(tan(1:10)))
  > x[do.call("order", split(x, col(x))), , drop=FALSE]
        [,1] [,2] [,3]
   [1,]   -1   -1    1
   [2,]   -1   -1    1
   [3,]   -1    0   -3
   [4,]    0   -1    0
   [5,]    0   -1    0
   [6,]    0    1    0
   [7,]    1    0   -7
   [8,]    1    0   -2
   [9,]    1    1    1
  [10,]    1    1    2

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 Maxim
> Sent: Friday, September 23, 2011 9:22 AM
> To: r-help
> Subject: [R] sorting multiple columns of a matrix
> 
> Hi,
> 
> 
> I have a question about how to sort a matrix for multiple columns.
> 
> 
> dat<-sample(0:1,1000,replace=T)
> 
> matrix(dat,ncol=5,nrow=200)->x
> 
> 
> I want to order like the following:
> 
> 
> x[order(x[,1],x[,2],x[,3],x[,4],x[,5]),]->x
> 
> 
> My problem: the number of columns of the matrix to be sorted is variable, in
> any way I would like to sort for all columns from 1:ncol(x). How to achieve
> this?
> 
> 
> Best
> 
> 
> Maxim
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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