# 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[order(df\$column_name), ]`

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

`df[order(df\$column_name, decreasing=TRUE), ]`

In the examples below, you’ll also observe how to sort a DataFrame based on multiple columns.

## 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")
)
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_sorted_by_name_asc <- df[order(df\$name), ]
df_sorted_by_name_asc```

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_sorted_by_name_desc <- df[order(df\$name, decreasing=TRUE), ]
df_sorted_by_name_desc```

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_sorted_by_gender_and_age_asc <- df[order(df\$gender, df\$age), ]
df_sorted_by_gender_and_age_asc```

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``````
Categories R