The last few sections in this chapter require one to rank a data set. To rank a data set, you first must arrange the data from smallest to largest. The smallest value gets a rank of 1, the next smallest gets a rank of 2, etc. If there are any values that tie, then each of the tied values gets the average of the corresponding ranks.
# rank() averages tied ranks by default - exactly the midrank rule above
x <- c(8, -4, 1, -3, 5, 2, -3, 0, 5, 3, 5)
data.frame(sorted = sort(x), rank = rank(sort(x)))
# -> 1, 2.5, 2.5, 4, 5, 6, 7, 9, 9, 9, 11 (both -3s share 2.5; the three 5s share 9)
# Second sample: what rank does 15 get?
y <- c(10, 25, 15, 8, 20, 15, 10, 9, 8, 22)
rank(y)[y == 15] # -> 6.5
# Change one value to break a tie and watch the whole rank column shift
Adapted from Mostly Harmless Statistics by Rachel Webb (Portland State University), hosted on LibreTexts (stats.libretexts.org) and licensed under CC BY-SA 4.0. Changes were made. License: CC-BY-SA-4.0.