[R] Summary: Re: Q: sort a matrix by picking up columns?
Yuyun Jessie Yang
yuyun at stat.wisc.edu
Sun Oct 17 18:37:22 CEST 1999
Thank Douglas Bates, Jan Schelling, Renaud Lancelot for teaching me the
do.call() function, and thank John Bjornar Bremnes for teaching me the
format() function. I would like to also thank the others who contribute
their inputs. Here is a brief summary of replies so far.
A function shown below will do what I need:
(This is copied from Renaud Lancelot's reply to r-help list.)
> SortMat <- function(Mat, Sort)
m <- do.call("order", as.data.frame(Mat[, Sort]))
Another trick by John Bjornar Bremnes also works on my small elemantary
example. It helped me learn another function format(). I haven't tried it
on my bigger data sets yet though:
a <- c(1,3,6,8,10,13)
Mat[ order( apply(format(Mat[,a]), 1, paste, collapse="") ), ]
==================== the original question =========================
On Wed, 13 Oct 1999, Yuyun Jessie Yang wrote:
> I am wondering how to write a function which sorts a matrix by giving a
> vector of column numbers.
> Suppose we have a matrix (or data frame) "Mat" and I want to obtain
> order(Mat[,1], Mat[,3], Mat[,6,], Mat[,8], Mat[,10], Mat[,13])
> in order to sort the matrix by those columns. Is there a way to write a
> function so that I can give a vector of the column numbers
> c(1,3,6,8,10,13) and do the sorting? Here we know that we cannot just
> write order(Mat[,c(1,3,6,8,10,13)]), which would give a wrong answer.
> Thanks for any input.
> Yuyun Jessie Yang
> Dissertator, Department of Statistics
> University of Wisconsin-Madison
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
More information about the R-help