0Pricing
R Academy · Lesson

Sorting Vectors with sort()

Sort numeric and character vectors in ascending or descending order.

What Does sort() Do?

The sort() function arranges a vector's elements in ascending order by default. It works on numeric, character, and logical vectors, returning a new sorted vector without modifying the original.

scores <- c(42, 7, 95, 13, 67, 31)
sorted_scores <- sort(scores)
print(sorted_scores)

Sorting in Descending Order

Pass decreasing = TRUE to sort() to flip the order. This is useful for ranking results from highest to lowest, such as leaderboard scores or sales figures.

prices <- c(19.99, 5.49, 89.00, 34.50, 12.75)
sort(prices, decreasing = TRUE)

All lessons in this course

  1. Sorting Vectors with sort()
  2. order() for Flexible Ordering
  3. Ranking Values with rank()
  4. Sorting Data Frames by Column
← Back to R Academy