0
0
R Programmingprogramming~5 mins

arrange() for sorting in R Programming

Choose your learning style9 modes available
Introduction

The arrange() function helps you put your data in order. It sorts rows in a table by one or more columns, making it easier to find or compare information.

You want to see the highest or lowest values in a list clearly.
You need to organize data by date to understand trends over time.
You want to sort names alphabetically to find a person quickly.
You are preparing data for a report and want it neatly ordered.
You want to group similar items together by sorting on a category.
Syntax
R Programming
arrange(data_frame, column1, column2, ...)
arrange(data_frame, desc(column))

Use arrange() from the dplyr package.

Use desc() inside arrange() to sort in descending order.

Examples
Sorts the data frame df by the age column in ascending order.
R Programming
arrange(df, age)
Sorts df by the score column in descending order.
R Programming
arrange(df, desc(score))
Sorts df first by city alphabetically, then by age ascending within each city.
R Programming
arrange(df, city, age)
Sample Program

This program creates a small table of people with their names, ages, and cities. It first sorts the table by age from youngest to oldest, then sorts by city alphabetically and within each city by age from oldest to youngest.

R Programming
library(dplyr)

# Create a sample data frame
people <- data.frame(
  name = c("Anna", "Ben", "Clara", "David"),
  age = c(28, 22, 35, 22),
  city = c("New York", "Boston", "Boston", "Chicago")
)

# Sort by age ascending
sorted_by_age <- arrange(people, age)
print(sorted_by_age)

# Sort by city ascending, then age descending
sorted_by_city_age <- arrange(people, city, desc(age))
print(sorted_by_city_age)
OutputSuccess
Important Notes

Remember to load the dplyr package with library(dplyr) before using arrange().

If you want to sort by multiple columns, list them in the order you want to sort.

Sorting does not change your original data unless you save the result.

Summary

arrange() sorts rows in a data frame by one or more columns.

Use desc() inside arrange() to sort in descending order.

It helps organize data to find or compare information easily.