How to Sort a DataFrame in R

The order() function can be used to sort a DataFrame in R:

(1) Sort a DataFrame based on a single column in an ascending order:

df <- df[order(df$column_name), ]

(2) Sort a DataFrame based on a single column in a descending order:

df <- df[order(df$column_name, decreasing=TRUE), ]

Examples of Sorting a DataFrame in R

Example 1: Sort a DataFrame based on a single column in an ascending order

To start, create the following DataFrame in R with 3 columns:

df <- data.frame(
name = c("Maria", "Bill", "Rick", "Tina", "Dave"),
age = c(29, 38, 52, 33, 41),
gender = c("Female", "Male", "Male", "Female", "Male")
)

print(df)

Here is the DataFrame, which is currently unsorted:

   name  age  gender
1 Maria   29  Female
2  Bill   38    Male
3  Rick   52    Male
4  Tina   33  Female
5  Dave   41    Male

To sort the DataFrame based on the “name” column in an ascending order:

df <- data.frame(
name = c("Maria", "Bill", "Rick", "Tina", "Dave"),
age = c(29, 38, 52, 33, 41),
gender = c("Female", "Male", "Male", "Female", "Male")
)

df <- df[order(df$name), ]

print(df)

The result is a sorted DataFrame based on the “name” column in an ascending order:

   name  age  gender
2  Bill   38    Male
5  Dave   41    Male
1 Maria   29  Female
3  Rick   52    Male
4  Tina   33  Female

Example 2: Sort a DataFrame based on a single column in a descending order

To sort the DataFrame based on the “name” column in a descending order:

df <- data.frame(
name = c("Maria", "Bill", "Rick", "Tina", "Dave"),
age = c(29, 38, 52, 33, 41),
gender = c("Female", "Male", "Male", "Female", "Male")
)

df <- df[order(df$name, decreasing=TRUE), ]

print(df)

The sorted DataFrame:

   name  age  gender
4  Tina   33  Female
3  Rick   52    Male
1 Maria   29  Female
5  Dave   41    Male
2  Bill   38    Male

Example 3: Sort a DataFrame based on multiple columns

To sort a DataFrame based on the “gender” AND the “age” columns in an ascending order:

df <- data.frame(
name = c("Maria", "Bill", "Rick", "Tina", "Dave"),
age = c(29, 38, 52, 33, 41),
gender = c("Female", "Male", "Male", "Female", "Male")
)

df <- df[order(df$gender, df$age), ]

print(df)

The sorted DataFrame:

   name  age  gender
1 Maria   29  Female
4  Tina   33  Female
2  Bill   38    Male
5  Dave   41    Male
3  Rick   52    Male

Leave a Comment