sort()
sort(x, decreasing = FALSE, na.last = NA) Returns:
vector of same type as x · Updated March 13, 2026 · Base Functions sorting vectors base ordering
sort() arranges the elements of a vector in ascending order by default. It preserves the type of the input vector and handles NA values with the na.last parameter.
Syntax
sort(x, decreasing = FALSE, na.last = NA)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | vector | — | A vector to sort |
decreasing | logical | FALSE | If TRUE, sorts in descending order |
na.last | logical or NA | NA | Controls placement of NA values |
Examples
Basic usage
# Sort a numeric vector
numbers <- c(5, 2, 8, 1, 9)
sort(numbers)
# [1] 1 2 5 8 9
# Sort in descending order
sort(numbers, decreasing = TRUE)
# [1] 9 8 5 2 1
Handling NA values
# By default, NA goes to the end
vec <- c(3, NA, 1, 2, NA)
sort(vec)
# [1] 1 2 3 NA NA
# Put NA first
sort(vec, na.last = FALSE)
# [1] NA NA 1 2 3
# Remove NA values
sort(vec, na.last = NA)
# [1] 1 2 3
Sorting character vectors
names <- c("Charlie", "Alice", "Bob")
sort(names)
# [1] "Alice" "Bob" "Charlie"
Common Patterns
Sort a data frame by column
df <- data.frame(name = c("Charlie", "Alice", "Bob"), score = c(85, 92, 78))
df[order(df$score), ]
# name score
# 3 Bob 78
# 1 Charlie 85
# 2 Alice 92
Get order indices
# Use order() to get indices instead of sorted values
x <- c("b", "a", "c")
order(x)
# [1] 2 1 3
x[order(x)]
# [1] "a" "b" "c"