How to Sort Data Frames by Column in R with arrange()
Sort data frames by column to reorder rows in ascending or descending order. Both dplyr::arrange() and order() perform stable sorts: tied rows keep their original relative order. With factor columns, R sorts by factor level order rather than alphabetically — convert with as.character() first to force alphabetic sorting.
library(dplyr)
# Sort by salary descending, then by department ascending
df %>%
arrange(desc(salary), department)
Base R uses df[order(-df$salary), ] for descending numeric columns. The - prefix only works with numeric values; for character columns, use df[order(df$name, decreasing = TRUE), ].
# Base R: sort by department then descending salary
df[order(df$department, -df$salary), ]
Data.table provides setorder(), which sorts in place without copying, useful for large datasets. Both arrange() and order() accept multiple column arguments where ties in earlier columns are broken by later ones. Missing values always sort to the end regardless of sort direction. For a descending sort on all columns at once, use arrange(across(everything(), desc)) with dplyr. To sort a data frame by row names, use df[order(rownames(df)), ] with base R. Use na.last = NA in order() to drop NA rows entirely from the sorted result rather than placing them at the end.