How to Calculate the Mode in R

This is something I keep looking up, because for whatever reason R does not come with a built-in function to calculate the mode. (The mode() function does something else, not what I’d expect given that there are mean() and median()…) It’s quite easy to write a short function to calculate the mode in R:

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

P.S.

Added 3 December 2019:

Here’s a tweak that does work with NA in the data.

Mode = function(x) {
ux = na.omit(unique(x))
return(ux[which.max(tabulate(match(x, ux)))])
}

Published 26 September 2016