0Pricing
R Academy · Lesson

Ranking Values with rank()

Assign ranks with tie-breaking methods: average, first, min, max, random.

Ranking Values with rank() is a free R Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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')

Ties Method: first and last

ties.method = 'first' assigns the lower rank to whichever tied element appears first in the vector. 'last' does the opposite — the earlier element gets the higher rank.

x <- c(10, 20, 20, 30)
cat('first:', rank(x, ties.method = 'first'), '\n')
cat('last: ', rank(x, ties.method = 'last'),  '\n')

Ties Method: min and max

'min' gives all tied elements the minimum rank they could have (used in sports: two players tied for 3rd both get rank 3, nobody gets rank 4). 'max' gives all tied elements the maximum rank.

x <- c(10, 20, 20, 30)
cat('min:', rank(x, ties.method = 'min'), '\n')
cat('max:', rank(x, ties.method = 'max'), '\n')

Ties Method: random

ties.method = 'random' breaks ties by randomly assigning distinct ranks among tied elements. Each call may produce a different result. Useful when you need unique integer ranks but do not care about tie-breaking order.

x <- c(10, 20, 20, 20, 30)
set.seed(42)
cat('random run 1:', rank(x, ties.method = 'random'), '\n')
set.seed(99)
cat('random run 2:', rank(x, ties.method = 'random'), '\n')

Dense Ranking vs Standard Ranking

R's rank() produces standard competition ranking (1, 2, 2, 4). For dense ranking (1, 2, 2, 3 — no gaps), use rank(x, ties.method = 'min') on unique values, or use the data.table or dplyr packages. Here is a base-R workaround:

x <- c(10, 20, 20, 30)
# Standard ranking (gaps after ties)
cat('Standard:', rank(x, ties.method = 'min'), '\n')
# Dense ranking: rank of sorted unique values
dense <- match(x, sort(unique(x)))
cat('Dense:   ', dense, '\n')

rank() vs order() vs sort()

These three functions are related but return different things: sort(x) returns sorted values, order(x) returns positions that sort the vector, and rank(x) returns the rank of each position. Here is a side-by-side comparison.

x <- c(30, 10, 50, 20, 40)
cat('x       :', x,        '\n')
cat('sort(x) :', sort(x),  '\n')
cat('order(x):', order(x), '\n')
cat('rank(x) :', rank(x),  '\n')

Ranking in Descending Order

To rank from largest to smallest (rank 1 = highest value), negate the vector before passing it to rank(). This is the pattern for leaderboards where rank 1 means best.

scores <- c(78, 92, 65, 88, 71)
desc_ranks <- rank(-scores)
cat('Scores:      ', scores,     '\n')
cat('Rank (best=1):', desc_ranks, '\n')

Adding Ranks to a Data Frame

A common task is adding a rank column to a data frame. Use rank() with ties.method = 'min' and negate for descending to build a proper leaderboard.

df <- data.frame(
  player = c('Alice', 'Bob', 'Carol', 'Dave'),
  score  = c(250, 400, 250, 375)
)
df$rank <- rank(-df$score, ties.method = 'min')
df[order(df$rank), ]

rank() with NA Values

rank() has an na.last argument just like sort() and order(). The default is 'keep', which assigns NA rank to NA values while ranking the non-NA elements among themselves.

x <- c(5, NA, 2, NA, 8, 1)
cat('na.last=keep:  ', rank(x, na.last = 'keep'), '\n')
cat('na.last=TRUE:  ', rank(x, na.last = TRUE),   '\n')
cat('na.last=FALSE: ', rank(x, na.last = FALSE),  '\n')

Percentile Ranks

Convert ranks to percentiles by dividing by the total count. A percentile rank tells you what fraction of values are at or below a given element. This is useful in statistics and educational scoring.

scores <- c(60, 75, 82, 91, 68, 77, 85, 95)
n <- length(scores)
pct_rank <- rank(scores) / n * 100
result <- data.frame(score = scores, percentile = round(pct_rank, 1))
result[order(result$score), ]

Quick Check

Which ties.method gives all tied elements the same lowest possible rank (like sports where two players share 3rd place and nobody gets 4th)?

rank() Key Takeaways

Key takeaways for rank():

  • rank(x) returns the rank of each element (same length as input)
  • Default ties.method = 'average': tied elements share the mean of their ranks
  • 'min' = sports-style (shared lowest rank), 'max' = shared highest rank
  • 'first' and 'last' break ties by order of appearance
  • Use rank(-x) for descending ranks (rank 1 = largest value)
  • Add rank columns to data frames with df$rank <- rank(-df$score, ties.method='min')
x <- c(10, 30, 20, 30, 10)
cat('average:', rank(x, ties.method = 'average'), '\n')
cat('min:    ', rank(x, ties.method = 'min'),     '\n')
cat('max:    ', rank(x, ties.method = 'max'),     '\n')
cat('first:  ', rank(x, ties.method = 'first'),   '\n')

Frequently asked questions

Is the “Ranking Values with rank()” lesson free?

Yes — the full text of “Ranking Values with rank()” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “Ranking Values with rank()”?

Assign ranks with tie-breaking methods: average, first, min, max, random. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Ranking Values with rank()” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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