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

order()

order works out the positions that would sort a list, like a seating plan telling everyone where to stand. You can use it to rearrange a whole table by one column.

In this page:

  1. order()
Syntax
r
sorted_indices <- order(x)
x[order(x)]
df[order(df$column, decreasing = TRUE), ]

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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing df[order(df$age)] without the comma, which sorts columns instead of rows; write df[order(df$age), ].
  2. Using order for descending order without decreasing = TRUE or a minus sign.
  3. Expecting order(x) to return the sorted values, when it returns the positions; use sort(x) for the values.
🔒

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.