order() for Flexible Ordering
Get the index permutation to sort by one or multiple criteria.
What order() Returns
order() does not return sorted values — it returns the indices that would sort the vector. This indirection makes it far more powerful than sort() because you can apply those indices to any related structure.
x <- c(30, 10, 50, 20, 40)
indices <- order(x)
print(indices)
# Verify: x[indices] gives sorted x
print(x[indices])order() in Descending Order
Like sort(), order() accepts decreasing = TRUE to return indices that produce a descending sequence. This is useful for sorting from largest to smallest.
scores <- c(78, 92, 65, 88, 71)
desc_order <- order(scores, decreasing = TRUE)
cat('Rank order (index):', desc_order, '\n')
cat('Scores high to low:', scores[desc_order], '\n')All lessons in this course
- Sorting Vectors with sort()
- order() for Flexible Ordering
- Ranking Values with rank()
- Sorting Data Frames by Column