Closed duttashi closed 6 years ago
Your choices
order
from base
arrange
from dplyr
setorder
and setorderv
from data.table
arrange
from plyr
sort
from taRifx
orderBy
from doBy
sortData
from Deducer
Alternative Approach # 1
You can use the order()
function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order) code:
> dd[with(dd, order(-z, b)), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
Alternative Approach # 2
To do this by column index. The answer is to simply pass the desired sorting column(s) to the order()
function:
> dd[ order(-dd[,4], dd[,1]), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
Alternative Approach # 3
You can also use the arrange()
function from plyr
library(plyr)
arrange(dd,desc(z),b)
Alternative Approach # 4
The dplyr
way;
library(dplyr)
# sort mtcars by mpg, ascending... use desc(mpg) for descending
arrange(mtcars, mpg)
# sort mtcars first by mpg, then by cyl, then by wt)
arrange(mtcars , mpg, cyl, wt)
In reference to the question, arrange()
can be used as given:
arrange(dd, desc(z), b)
b x y z
1 Low C 9 2
2 Med D 3 1
3 Hi A 8 1
4 Hi A 9 1
I want to sort a data.frame by multiple columns. For example, with the data.frame below I would like to sort by column z (descending) then by column b (ascending):