Sorting DataFrame in R using Dplyr
In this article, we will discuss about how to sort a dataframe in R programming language using Dplyr package. The package Dplyr in R programming language provides a function called arrange() function which is useful for sorting the dataframe.
The methods given below show how this function can be used in various ways to sort a dataframe.
Sorting in Ascending order
Sorting in ascending order is the default sorting order in arrange() function. The attribute to sort by should be given as an argument to this function.
Example: Sorting the dataframe in ascending order
Sorting in Descending order
For sorting our dataframe in descending order, we will use desc() function along with the arrange() function. We will also use % operator for comparison of the dataframe column which we are taking for sorting purpose.
Example: Sorting the dataframe in descending order
Sorting the dataframe using multiple variables
We will now sort our dataframe using multiple variables using the arrange() function. The attributes should be given to the function separated by a column. For example, in the given example the dataframe is sorted by salary column in descending order and product column in ascending order. We will use the % operator for comparing data to be sorted in descending order.
Example: Sorting the dataframe using multiple variables