← Back to R Course | Chapter 8: Data Manipulation | Lesson 5 of 7

order()

In this page:

  1. order()

order()

order(x) returns the indices that would sort x, rather than the sorted values themselves -- this is what lets you sort a whole data frame by one column while keeping other columns aligned. df[order(df$col), ] is the standard idiom for sorting a data frame by a column. Add a minus sign, like order(-df$col), to sort descending.

Note: df[order(df$col), ] is the standard idiom for sorting an entire data frame by one of its columns.

Example: order()

markup
df <- data.frame(name = c("Cara", "Alice", "Bob"), age = c(40, 30, 25))

sorted_df <- df[order(df$age), ]
print(sorted_df)
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.