Sorting DataFrame in R using Dplyr – arrange function

Sorting dataframe in R can be done using Dplyr. Dplyr package in R is provided with arrange() function which sorts the dataframe by multiple conditions.

We will be using mtcars data to depict the example of sorting with arrange() function.

library(dplyr)
mydata <- mtcars

# sort the dataframe in R
arrange(mydata,mpg)

The default sorting order of arrange() function is ascending.

Sorting dataframe in R using Dplyr using arrange function 1

 

Sorting dataframe in R using multiple variables with Dplyr:

In this example, we are sorting data by multiple variables. One in descending and one in ascending the example is shown below. We will be using pipe operator  (%>%).

# sort the dataframe in R using multiple variable with Dplyr
mydata %>% arrange(desc(mpg)) %>% arrange(gear)

pipe operator first sorts the mpg in descending order format and within that it sorts gear in ascending order format.

Sorting dataframe in R using Dplyr using arrange function 2

 

Sorting DataFrame in R using Dplyr                                                                                                                Sorting DataFrame in R using Dplyr