R Vector Sort

R gives you several tools for putting a vector's elements in order, each suited to a different sorting need.

Sorting Values with sort()

The sort() function returns a new vector with its elements arranged from smallest to largest by default. It works on numeric vectors and character vectors alike, and it leaves the original vector untouched unless you reassign the result.

Example

temps <- c(72, 65, 90, 58, 81)

sort(temps)
sort(temps, decreasing = TRUE)

friends <- c("Maya", "Ben", "Zoe", "Amir")
sort(friends)

Finding the Order with order()

sort() rearranges the values themselves, but sometimes you need to know which position each value came from - for example, to rearrange a whole table by one column. order() returns the indices that would put the vector in sorted order, and you can reuse those indices to reorder related vectors together.

Using order()

temps <- c(72, 65, 90, 58, 81)
cities <- c("Austin", "Denver", "Miami", "Boise", "Tampa")

idx <- order(temps)
idx

temps[idx]
cities[idx]

Reversing a Vector with rev()

rev() simply flips the order of a vector's elements without comparing their values at all. It's often combined with sort() to get a descending order, though sort(x, decreasing = TRUE) achieves the same result more directly.

Reversing

letters_sample <- c("d", "a", "c", "b")

rev(letters_sample)
rev(sort(letters_sample))
FunctionPurposeExample
sort(x)Returns values in ascending ordersort(c(3,1,2)) -> 1 2 3
order(x)Returns the indices that would sort xorder(c(3,1,2)) -> 2 3 1
rev(x)Reverses element order as-isrev(c(1,2,3)) -> 3 2 1
Note: By default, sort() drops any NA values it finds. If you want to keep them, use sort(x, na.last = TRUE) to push them to the end instead of silently removing them.
  • Use sort() when you only care about the values themselves.
  • Use order() when you need to rearrange several related vectors, or a data frame's rows, using the same order.
  • Use rev() when you want to flip a vector that may already be sorted, or reverse any arbitrary sequence.