Skip to main content
v2026.11,986 entries · CC-BY 4.0

Rank in R: rank() Syntax, Ties and Worked Examples

How to rank values in R with rank(): arguments, all six tie methods on one vector, descending order, NA handling and dplyr equivalents.

Written and maintained by CASRAI Editorial Board

Published

On this page

To rank values in R, call rank(x): it returns, for each element of the vector x, its position in the sorted order, with the smallest value getting rank 1. Ties get the mean of the positions they share by default (ties.method = "average"), and missing values are ranked last unless you change na.last. The function is part of base R, so nothing needs installing.

What rank() is used for in research

Ranking replaces raw values with their order. That is the first step of every rank-based method: Spearman’s correlation is the Pearson correlation of the ranks, and tests such as Wilcoxon and Kruskal-Wallis work on ranks rather than raw measurements. If you are choosing between a parametric and a rank-based method, the CASRAI guide to nonparametric statistics explains when the switch is warranted, and the worked page on calculating Spearman correlation shows what the ranks feed into.

Ranks are also used outside inference. Research offices and analysts rank institutions, journals or applications by a score, and need to decide what happens when two entries tie. The same choice, average, minimum or consecutive positions, appears in the percentile-from-rank calculation, which is why the tie rule deserves a deliberate decision rather than the default.

Two things make rank() easy to misuse. It returns the rank of each element in its original position, not a sorted copy of the data, and it ranks ascending only. The sections below cover the arguments, the six tie methods side by side on one vector, descending ranks, missing values and the tidyverse and data.table equivalents.

How to install or access rank() in R

The rank() function belongs to the base package, which is loaded in every R session. You only need R itself. R is distributed from the Comprehensive R Archive Network (CRAN) at cran.r-project.org, and the official R Installation and Administration manual describes building and installing it. The CASRAI page on installing R covers the workflow from download to first session.

Two optional packages offer rank functions with extra features. Install them once from CRAN and load them in each session:

  1. install.packages("dplyr") then library(dplyr) gives row_number(), min_rank() and dense_rank().
  2. install.packages("data.table") then library(data.table) gives frank().

To read the built-in documentation for the base function, type ?rank at the R prompt.

How to rank values in R step by step

The signature, as documented in the base R 4.6.0 manual, is:

rank(x, na.last = TRUE,     ties.method = c("average", "first", "last", "random", "max", "min"))

x may be a numeric, complex, character or logical vector. na.last controls missing values and ties.method controls ties; the method name can be abbreviated.

Step 1. Rank a vector with no ties

  1. Create a vector: x1 = c(3, 1, 4, 15, 92).
  2. Call rank(x1). The result is 2 1 3 4 5: 3 is the second smallest value, 1 the smallest, and so on.

With no ties and no missing values, the ranks are a permutation of seq_along(x), so the choice of ties.method makes no difference.

Step 2. Rank a vector with ties

  1. Create the vector the R manual itself uses: x2 = c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5).
  2. Call rank(x2). Positions 2 and 4 both hold the value 1, which would occupy ranks 1 and 2, so each receives 1.5. The three 5s would occupy ranks 7, 8 and 9, so each receives 8. The full result is 4.5 1.5 6.0 1.5 8.0 11.0 3.0 10.0 8.0 4.5 8.0.

Step 3. Choose the tie method

The manual defines each method. "average" replaces tied values by their mean rank; "min" and "max" give every tied value the lowest or highest rank in the group, with "min" described as the typical sports ranking; "first" produces a permutation with increasing values at each set of ties, and "last" the same with decreasing values; "random" puts them in random order. Applied to x2, the six methods give the following ranks, listed in the order of the elements of x2.

ties.method Ranks for x2 = 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5
“average” 4.5, 1.5, 6, 1.5, 8, 11, 3, 10, 8, 4.5, 8
“first” 4, 1, 6, 2, 7, 11, 3, 10, 8, 5, 9
“last” 5, 2, 6, 1, 9, 11, 3, 10, 8, 4, 7
“min” 4, 1, 6, 1, 7, 11, 3, 10, 7, 4, 7
“max” 5, 2, 6, 2, 9, 11, 3, 10, 9, 5, 9
“random” varies between calls: ties are ordered at random

For reproducible results with "random", set a seed with set.seed() before the call. The manual’s own checks give a useful consistency test: the “max” ranks plus the “min” ranks equal twice the average ranks, which holds in every column above.

Step 4. Rank in descending order

rank() has no argument for direction. For a numeric vector, negate it: rank(-x2) gives the largest value rank 1. Under the default average method the 9 receives rank 1, the 6 rank 2, the three 5s the average rank 4 and the two 1s the average rank 10.5. In dplyr, wrap the input in desc(), and in data.table, frank() accepts order = -1 or a unary minus to request descending order.

Step 5. Handle missing values

By default na.last = TRUE puts missing values last and gives each a distinct rank, because the manual states that NA values are never considered equal. The other settings are FALSE (first), NA (remove them from the result) and "keep" (keep them with rank NA). For y = c(5, 1, 3, 2, 2, NA):

Call Result
rank(y) 5, 1, 4, 2.5, 2.5, 6
rank(y, na.last = "keep") 5, 1, 4, 2.5, 2.5, NA
rank(y, na.last = NA) 5, 1, 4, 2.5, 2.5 (the missing value is dropped)

For analysis, "keep" is usually the safest choice, because the output stays the same length as the input and a missing score is never silently given a rank.

How to read the output

The result is a vector the same length as x, with names copied from x. If x2 has names, as in the manual’s example names(x2) = letters[1:11], each rank carries the name of its element, which makes a result easy to match back to the observations.

The type of the result depends on the method. According to the manual the vector is of integer type unless x is a long vector or ties.method = "average", in which case it is of double type, whether or not there are any ties. So rank(c(3, 1, 4, 15, 92)) returns doubles that print as whole numbers, while rank(x, ties.method = "min") returns integers.

Because ranking an already ranked vector changes nothing, rank(rank(x)) == rank(x) is true. The manual calls this idempotent.

rank() compared with order()

These two are often confused. rank(x) says where each element would sit in the sorted vector. order(x) returns a permutation: the indices that rearrange x into sorted order, with ties broken by further arguments and in a stable way. For x = c(30, 10, 20), rank(x) is 3 1 2 while order(x) is 2 3 1. Use rank() when you want a score per observation and order() when you want to sort a data frame; the guide to ordering data in R covers the latter. Without ties, one is the inverse of the other, so order(order(x)) equals rank(x).

Ranks within groups

Base R’s rank() ranks the whole vector. To rank within groups, dplyr offers a direct route: after group_by(grp), the dplyr documentation uses filter(row_number(x) == 1) to take exactly one row per group, and filter(min_rank(x) == 1) to keep every tied minimum, which can return more than one row.

Troubleshooting rank()

  • The ranks contain decimals such as 1.5. This is the default average method on tied values. Use ties.method = "min" or "first" for whole numbers.
  • The smallest value should be rank 1 but you need the largest. Negate a numeric vector, rank(-x), or use desc() or frank(x, order = -1).
  • Results change between runs. You are using ties.method = "random". Set a seed or choose a deterministic method.
  • The output is longer than expected or has a rank for a missing value. The default na.last = TRUE gives missing values their own distinct ranks at the end. Use na.last = "keep".
  • You want to rank a whole data frame. The base function is documented for a vector. Rank one column at a time, for example rank(df$score), or use frank(), which accepts vectors, lists and data frames.
  • dplyr and base R disagree on missing values. The dplyr functions give missing values rank NA, and its documentation suggests coalesce(x, Inf) or coalesce(x, -Inf) to treat them as the largest or smallest values.
  • Character ranks differ between tools. data.table documents that frank() sorts characters in the C locale and treats NA values as identical, unlike base rank(), so compare outputs before swapping one for the other.

Free alternatives to base rank()

The base function covers most needs. The packages below add speed, tidy-style grouping or an extra tie rule. The table maps each tie rule to the nearest function; the data table below it sets the same comparison against the ranks each rule gives for tied values in the example vector.

Tool Function What it adds
base R rank() Six tie methods and four na.last settings on a vector.
dplyr row_number(), min_rank(), dense_rank() Work inside mutate() and filter() with grouped data. For c(10, 20, 20, 30) they give 1, 2, 3, 4; 1, 2, 2, 4; and 1, 2, 2, 3.
data.table frank() Documented as similar to base::rank but much faster; adds the "dense" method and accepts data frames.
Python SciPy scipy.stats.rankdata() For work outside R: methods average, min, max, dense and ordinal, for example rankdata([0, 2, 3, 2], method='ordinal') returns [1, 2, 4, 3].

The dplyr page describes row_number() as equivalent to rank(ties.method = "first"), min_rank() as the ranking usually computed in sports, and dense_rank() as the version that leaves no gaps. The base R manual lists no dense method. Researchers comparing tools for wider statistical work can start from the CASRAI overview of free statistical software.

Sources

Data: How each tie rule ranks the tied values in c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5), by R and Python function

Compares tie-handling rules for rank functions in base R, dplyr, data.table and SciPy. For each rule it lists the equivalent function documented by each package and the ranks given to the two tied 1s and the three tied 5s in the example vector from the R base manual. The ranks were derived by applying each documented rule to that vector; function equivalences come from the four package manuals.

How each tie rule ranks the tied values in c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5), by R and Python function
Tie ruleBase R rank()dplyrdata.table frank()SciPy rankdata()Ranks given to the two 1sRanks given to the three 5s
averageties.method = "average" (default)none documented on the row_number pageties.method = "average" (default)method='average' (default)1.5, 1.58, 8, 8
minties.method = "min"min_rank()ties.method = "min"method='min'1, 17, 7, 7
maxties.method = "max"none documented on the row_number pageties.method = "max"method='max'2, 29, 9, 9
densenonedense_rank()ties.method = "dense"method='dense'1, 15, 5, 5
first / ordinalties.method = "first"row_number()ties.method = "first"method='ordinal'1, 27, 8, 9
lastties.method = "last"none documented on the row_number pageties.method = "last"none2, 19, 8, 7

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Rank in R: rank() Syntax, Ties and Worked Examples

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →