How to Calculate Statistical Mode in R
Calculate statistical mode to find the most frequent value in a vector. R has no built-in function for this — mode() returns the storage type of an object, not the most frequent value — so you need a short custom function that counts unique values and picks the one with the highest count. This recipe covers both a simple approach that returns the first mode and a tie-aware version that returns all modes when multiple values share the top frequency. The same pattern works on data frame columns by wrapping the logic inside dplyr::summarise().
get_mode <- function(x) {
x <- x[!is.na(x)]
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
x <- c(1, 2, 2, 3, 3, 3, 4, NA)
get_mode(x)
# [1] 3
This function strips NA values, finds the unique elements, then counts how often each appears with tabulate(). The which.max() call returns only the first mode — if there is a tie, you lose the other winning values.
For data frames, dplyr::count() with slice_head() does the same job in one pipeline:
library(dplyr)
df <- data.frame(color = c("red", "blue", "blue", "green", "green", "green"))
df %>% count(color, sort = TRUE) %>% slice_head(n = 1)
To return all modes when multiple values tie for the highest frequency, replace which.max() with equality against the max count:
get_mode <- function(x) {
x <- x[!is.na(x)]
ux <- unique(x)
tab <- tabulate(match(x, ux))
ux[tab == max(tab)]
}
See also
- unique(), Extract unique values from a vector
- table(), Cross-tabulation and frequency counts
- dplyr::count(), Count observations by group