order()

order(..., na.last = TRUE, decreasing = FALSE)
Returns: integer · Updated March 13, 2026 · Base Functions
sorting order base vector

order() returns the indices that would sort a vector or set of vectors. Unlike sort() which returns the sorted values, order() returns the positions that would reorder the data. This makes it essential for sorting data frames by one or multiple columns.

Syntax

order(..., na.last = TRUE, decreasing = FALSE)

Parameters

ParameterTypeDefaultDescription
...vectorsOne or more vectors to order by. Multiple vectors create hierarchical sorting.
na.lastlogicalTRUEHow to handle NA values: TRUE puts them at the end, FALSE at the beginning, NA removes them.,
decreasinglogicalFALSEIf TRUE, sort in descending order.

Examples

Basic usage

# Sort a numeric vector
x <- c(3, 1, 4, 1, 5, 9, 2, 6)
order(x)
# [1] 2 4 7 1 3 5 8 6

# Use the indices to reorder
x[order(x)]
# [1] 1 1 2 3 4 5 6 9

# Sort in descending order
x[order(x, decreasing = TRUE)]
# [1] 9 6 5 4 3 2 1 1

Sorting a data frame by multiple columns

df <- data.frame(
  name = c("Alice", "Bob", "Carol", "David", "Eve"),
  score = c(85, 92, 78, 92, 88),
  age = c(25, 30, 25, 30, 28)
)

# Sort by score (descending), then by age (ascending)
df[order(df$score, df$age, decreasing = c(TRUE, FALSE)), ]
#   name score age
# 2   Bob    92 30
# 4 David    92 30
# 5   Eve    88 28
# 1  Alice    85 25
# 3  Carol    78 25

Handling NA values

y <- c(2, NA, 1, 4, NA, 3)

# Default: NAs at the end
order(y)
# [1] 3 6 1 4 2 5

# NAs at the beginning
order(y, na.last = FALSE)
# [1] 2 5 3 6 1 4

# Remove NAs entirely
order(y, na.last = NA)
# [1] 3 6 1 4

Common Patterns

Using with dplyr: While dplyr::arrange() is more readable, order() is useful when you need the actual indices for complex operations.

# Find the top 3 values and their positions
x <- c(10, 45, 12, 67, 23, 89, 5)
idx <- order(x, decreasing = TRUE)[1:3]
x[idx]
# [1] 89 67 45

Stable sorting: order() in R is stable, meaning elements with equal keys maintain their relative order.

See Also