[R] sort (all columns of) a matrix
Bert Gunter
gunter.berton at gene.com
Thu Oct 8 22:32:33 CEST 2009
Bill:
Defensive programming seems to me to be a wise policy, so thanks for the
helpful tip.
-- Bert
Bert Gunter
Genentech Nonclinical Biostatistics
-----Original Message-----
From: William Dunlap [mailto:wdunlap at tibco.com]
Sent: Thursday, October 08, 2009 12:01 PM
To: Bert Gunter; Erik Iverson; Kajan Saied; r-help at r-project.org
Subject: RE: [R] sort (all columns of) a matrix
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Bert Gunter
> Sent: Thursday, October 08, 2009 11:41 AM
> To: 'Erik Iverson'; 'Kajan Saied'; r-help at r-project.org
> Subject: Re: [R] sort (all columns of) a matrix
>
> Right. My guess is that Kajan wants:
>
> a[do.call(order,data.frame(a)),]
> ## this generalizes to an arbitrary number of columns
> ## do.call() is a very powerful and useful R feature worth
> learning about
If you are compulsive wrap the second argument to do.call()
with unname(), just in case the data.frame has a column
with a name matching an argument to order (currently
'decreasing' and 'na.last'). This can save you from an
error like the following, where the 'decreasing' column
of 'd' is taken to be the 'decreasing' argument to order,
not just another column to sort:
> d<-data.frame(weight=c(190, 121, 167, 121),
decreasing=c(TRUE,TRUE,FALSE,FALSE))
> d[do.call(order,d),]
weight decreasing
1 190 TRUE
3 167 FALSE
2 121 TRUE
4 121 FALSE
> d[do.call(order,unname(d)),]
weight decreasing
4 121 FALSE
2 121 TRUE
3 167 FALSE
1 190 TRUE
At some point data.frame may take more pains to make sure its
instances all have column names, in which case the argument needs
to be wrapped with unname(as.list(...)).
(Internally order() can call do.call("order",...) without using unname
so it could run into the same problem.)
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
>
>
> Yet another reason why the posting guide asks for a simple, proper,
> reproducible example.
>
> -- Bert
>
> Bert Gunter
> Genentech Nonclinical Biostatistics
>
More information about the R-help
mailing list