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:
Syntax
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()
df <- data.frame(name = c("Cara", "Alice", "Bob"), age = c(40, 30, 25))
sorted_df <- df[order(df$age), ]
print(sorted_df)
Login to try C/C++/Java/PHP code in the editor
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
- Writing
df[order(df$age)]without the comma, which sorts columns instead of rows; writedf[order(df$age), ]. - Using
orderfor descending order withoutdecreasing = TRUEor a minus sign. - Expecting
order(x)to return the sorted values, when it returns the positions; usesort(x)for the values.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: