How to return an element rank of values of a vector in R

A vector's rank is its location relative to the other values in an ordered vector. For example, consider the vector v = c(8, 4, 10, 12, 6). The value 8 ranks 3 because it is the third largest value in the vector sorted in increasing order. Similarly, the rank of 4 is 1 because it is the vector's first lowest value.

The rank() function

By default, the rank() function in R gives the rank of each value in a vector as follows:

# creating a vector of values
v <- c(8, 4, 10, 12, 6)
# getting the rank of each value in the vector
rank(v)

The code above gives us the respective rank of each corresponding value in the vector.

Note: In R, the rank() function uses the competition ranking algorithmA method used to assign ranks to a list of items based on their numerical or alphabetical values. and assigns same ranks to items with the same value.

The rank of a particular element

Let's say we want to get the rank of a particular element in the vector. We use square bracket notation to extract that element first, then use the rank() as follows:

# creating a vector of values
v <- c(8, 4, 10, 12, 6)
# getting the rank of second element (i.e., 4) in the vector
rank(v[2])

The code above tells us that the second element in the vector has a rank of 1 because it is the vector's first-smallest value.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved