The arrange() function in R is “used to reorder the rows of a data frame/table using column names”. These columns are passed as the expression in the function.
Syntax
arrange(data, …, by_group=FALSE)
Parameters
- data: The data or table that we want to arrange.
- group_by: If set to true, .group_by will arrange by grouping the variables. This parameter only relates to grouped data frames.
- …: The list of variables, separated by a comma.
Example 1
if (!requireNamespace("dplyr", quietly = TRUE)) {
install.packages("dplyr")
}
# Load the dplyr package
library(dplyr)
# Create a sample data frame
df <- data.frame(
id = c(2, 1, 4, 5, 3),
name = c("John", "Mary", "Peter", "Lucy", "Sam"),
age = c(32, 27, 45, 23, 36)
)
# Sort the data frame by the 'id' column (ascending order)
sorted_data <- df %>%
arrange(id)
# Print the sorted data frame
print(sorted_data)
Output
id name age
1 1 Mary 27
2 2 John 32
3 3 Sam 36
4 4 Peter 45
5 5 Lucy 23
Example 2
To sort a column in descending order, you can use the “desc()” function inside the “arrange()” function.
if (!requireNamespace("dplyr", quietly = TRUE)) {
install.packages("dplyr")
}
# Load the dplyr package
library(dplyr)
# Create a sample data frame
df <- data.frame(
id = c(2, 1, 4, 5, 3),
name = c("John", "Mary", "Peter", "Lucy", "Sam"),
age = c(32, 27, 45, 23, 36)
)
# Sort the data frame by the 'id' column (ascending order)
sorted_data <- df %>%
arrange(desc(age))
# Print the sorted data frame
print(sorted_data)
Output
id name age
1 4 Peter 45
2 3 Sam 36
3 2 John 32
4 1 Mary 27
5 5 Lucy 23
Example 3
Using the dplyr arrange() function, you can also order multiple columns. While doing this, you can also specify one ascending column and another in descending order.
if (!requireNamespace("dplyr", quietly = TRUE)) {
install.packages("dplyr")
}
# Load the dplyr package
library(dplyr)
# Create a sample data frame
df <- data.frame(
id = c(2, 1, 4, 5, 3),
name = c("John", "Mary", "Peter", "Lucy", "Sam"),
age = c(32, 27, 45, 23, 36)
)
# Sort the data frame by the 'id' column (ascending order)
sorted_data <- df %>%
arrange(id, desc(age))
# Print the sorted data frame
print(sorted_data)
Output
id name age
1 1 Mary 27
2 2 John 32
3 3 Sam 36
4 4 Peter 45
5 5 Lucy 23
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.