Ranking Values with rank()
Assign ranks with tie-breaking methods: average, first, min, max, random.
What rank() Returns
rank(x) returns the sample ranks of the values in a vector. The smallest value gets rank 1, the second smallest gets rank 2, and so on. Unlike order(), the output has the same length as the input, with each position holding its rank.
scores <- c(78, 92, 65, 88, 71)
ranks <- rank(scores)
print(scores)
print(ranks)Handling Ties: Average Method
When values are equal (tied), rank() uses the ties.method argument to decide how to assign ranks. The default is 'average': tied elements receive the mean of the ranks they would have occupied.
x <- c(10, 20, 20, 30)
# Default: average of positions 2 and 3 = 2.5
rank(x)
rank(x, ties.method = 'average')All lessons in this course
- Sorting Vectors with sort()
- order() for Flexible Ordering
- Ranking Values with rank()
- Sorting Data Frames by Column