Calculate the Mode in R

Your goal

You need to calculate the mode of numerical or categorical data in R.

Step-by-step tutorial

Strangely, R doesn't have a built-in function for calculating the statistical mode of a dataset. There is a mode function, but it deals with the storage mode of an object, not the statistical mode of a set of data.

So to calculate the mode, we'll need to write our own function. We'll use a pair of functions due to Ken Williams on Stack Overflow:

# For a single mode
Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

# For multiple modes
Modes <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux))
  ux[tab == max(tab)]
}

Now we can use these as follows:

> Mode(c("apple", "apple", "banana", "cherry"))
[1] "apple"
> Modes(c("apple", "apple", "banana", "cherry", "cherry"))
[1] "apple"  "cherry"