Sorting a data frame according to multiple columns in R

r

#1

Hi,

I have a data frame and I want to sort it according to two columns, first in ascending order by column z and then by column y in descending order.

DF
w x y z
1 High A 2 1
2 Medium D 4 3
3 High A 8 1
4 Low C 8 2

How can I do this?

Thanks.


#2

use order function

dd[with(dd, order(z,-b)), ]

see -


#3

Alternatively, dplyr library’s arrange() function can be used.

library(nycflights13)
library(dplyr)
dplyr::arrange(flights,year,month,desc(day))  #Arranges by year,month and descending dates

-Nayan