How to Use arrange() Function in R

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

  1. data: The data or table that we want to arrange.
  2. group_by: If set to true, .group_by will arrange by grouping the variables. This parameter only relates to grouped data frames.
  3. : 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.

Leave a Comment