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
- Sorting Vectors with sort()
- order() for Flexible Ordering
- Ranking Values with rank()
- Sorting Data Frames by Column