tags:

views:

58

answers:

3

Is there a standard way of sorting a data.frame by several columns, but with changes in decrease or increase? For example, you may want to order a data.frame by one variable (decreasing) and by the next (increasing).

Is there something like:

mydf[ order(mydf$myvariable,mydf$myvariable2,decreasing=c(FALSE,TRUE)), ]
+2  A: 

Quick workaround:

 mydf[ order(mydf$myvariable,-mydf$myvariable2,decreasing=F), ]

For factors, strings etc:

 mydf[ order(mydf$myvariable,-xtfrm(mydf$myvariable2),decreasing=F), ]
mbq
It won't work for character/factor columns.
Marek
Good point, extended to handle that.
mbq
`xtfrm` is the function you're looking for
hadley
+2  A: 
library(plyr)
mydf[with(mydf, order(myvariable, desc(myvariable2)), ]

# Or, a little less typing:
arrange(mydf, myvariable, desc(myvariable2))
hadley
I like both answers, but admittedly I am a little biased towards the plyr package ;)
ran2
A: 
library(Deducer)
sort(mtcars,by = ~ cyl - mpg)
Ian Fellows