How to Sort Vectors in Descending Order in R
Sort vectors in descending order in R with sort(x, decreasing = TRUE). This returns a sorted copy without modifying the original. The same pattern works for numeric, character, and logical vectors — sort() handles each type with appropriate comparison semantics. For large datasets, add method = "radix" for the fastest sort.
x <- c(5, 2, 8, 1, 9)
sorted <- sort(x, decreasing = TRUE)
# [1] 9 8 5 2 1
For sorting a data frame column, dplyr::arrange(df, desc(col)) is the standard approach. order(x, decreasing = TRUE) returns permutation indices for reordering associated data. For character vectors, sort order is lexicographic and locale-dependent — uppercase letters come before lowercase in ASCII but the local collation may differ.
library(data.table)
dt <- data.table(value = c(5, 2, 8, 1, 9))
setorder(dt, -value)
Both sort() and order() accept decreasing = TRUE for descending order. The na.last argument controls whether NA values appear at the end (default) or are removed from the result entirely. For partial sorting where you only need the top or bottom N values, sort(x, partial = 1:10) returns only the first 10 elements in correct order, which is faster for very large vectors.