How to calculate the mode in R

· 2 min read · Updated March 15, 2026 · beginner
r statistics mode vectors dplyr

The mode is the value that appears most frequently in your data. Unlike mean and median, R has no built-in mode function, so you need to create one or use a package.

With base R

Create a simple function:

get_mode <- function(x) {
 ux <- unique(x)
 ux[which.max(tabulate(match(x, ux)))]
}

x <- c(1, 2, 2, 3, 3, 3, 4)
get_mode(x)
# [1] 3

This works by finding unique values, then counting how often each appears using tabulate().

Handle NA values:

get_mode <- function(x) {
  x <- x[!is.na(x)]
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

x <- c(1, 2, 2, NA, 3, 3, 3)
get_mode(x)
# [1] 3

With dplyr

Use count() and slice_max():

library(dplyr)

df <- data.frame(
  color = c("red", "blue", "blue", "green", "green", "green")
)

df %>%
  count(color, sort = TRUE) %>%
  slice_head(n = 1)
# # A tibble: 1 × 2
#   color     n
# 1 green     3

For a data frame column:

df %>%
  summarise(mode = count(color, sort = TRUE)$color[1])

With data.table

library(data.table)

dt <- data.table(color = c("red", "blue", "blue", "green", "green", "green"))
dt[, .N, by = color][order(-N)][1]
#    color N
# 1: green 3

Handling multiple modes

When you have tied values:

x <- c(1, 1, 2, 2)

get_mode <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux))
  ux[tab == max(tab)]
}

get_mode(x)
# [1] 1 2

This returns all values that share the highest frequency.

See Also

  • unique() — Extract unique values from a vector
  • table() — Cross-tabulation and frequency counts
  • dplyr::count() — Count observations by group