Sorting Data Frames by Column
Sort entire data frames using order() and dplyr's arrange().
Sorting a Data Frame by One Column
The standard base-R way to sort a data frame is to use order() on the column of interest and use the resulting indices to reorder the rows. The comma after the indices selects all columns.
df <- data.frame(
name = c('Charlie', 'Alice', 'Bob', 'Diana'),
age = c(35, 28, 42, 31),
salary = c(55000, 48000, 72000, 61000)
)
df[order(df$age), ]Sorting Descending with Negation
For numeric columns, negate the column inside order() to reverse the sort direction. The minus sign flips all values so that what was the maximum becomes the minimum for ordering purposes.
df <- data.frame(
name = c('Charlie', 'Alice', 'Bob', 'Diana'),
salary = c(55000, 48000, 72000, 61000)
)
# Highest salary first
df[order(-df$salary), ]All lessons in this course
- Sorting Vectors with sort()
- order() for Flexible Ordering
- Ranking Values with rank()
- Sorting Data Frames by Column