# How to sort a data frame in R by multiple columns together?

R ProgrammingServer Side ProgrammingProgramming

#### Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

We can sort a data frame by multiple columns using order function.

## Example

Consider the below data frame −

> df <- data.frame(x1 = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x2 = c("A", "B", "D", "C"), x3 = c(4, 7, 5, 3),
x4 = c(9, 5, 7, 4))
> df
x1 x2 x3 x4
1 Hi A 4 9
2 Med B 7 5
3 Hi D 5 7
4 Low C 3 4

Let’s say we want to sort the data frame by column x4 in descending order then by column x1 in ascending order.

It can be done follows −

> df[with(df, order(-x4, x1)), ]
x1 x2 x3 x4
1 Hi A 4 9
3 Hi D 5 7
2 Med B 7 5
4 Low C 3 4

We can do it by using column index as well −

> df[order(-df[,4], df[,1]), ]
x1 x2 x3 x4
1 Hi A 4 9
3 Hi D 5 7
2 Med B 7 5
4 Low C 3 4
Updated on 06-Jul-2020 12:33:58