Computing the mode in R

July 2, 2016

(This article was first published on My R Nightmares, and kindly contributed to R-bloggers)

In R there isn’t a function for computing the mode. This statistic is not often used but it is very useful for categorical and discrete data.

The mode is defined as “the most common value occurring in a set of observations.” Mathematically, for numerical data, the mode is the centre of order zero mode = arg min_m sum [x_i – m]^0, where 0^0 is defined as equal to 0.

This definition is not complete because in a set of data there can be one or many or no mode. For example: in a set with 10 apples, 5 pears and 2 bananas the mode is apple, in a set with 5 apples, 5 pears and 2 bananas the modes are apple and pear, in a set with 5 apples, 5 pears and 5 bananas there is no mode. This is shown in the figure below.

Hence a function that computes the mode needs to return one or many or no value. Furthermore, the values returned can be either characters or numbers (in case of discrete data). My solution is this:
Mode = function(x){
    ta = table(x)
    tam = max(ta)
    if (all(ta == tam))
         mod = NA
    mod = as.numeric(names(ta)[ta == tam])
         mod = names(ta)[ta == tam]

Let’s see how it works for nominal data:

One mode
fruit = c(rep(“apple”, 10), rep(“pear”, 5), rep(“banana”, 2))
# [1] “apple”

Two modes
fruit2 = c(rep(“apple”, 5), rep(“pear”, 5), rep(“banana”, 2))
# [1] “apple” “pear” 

No mode
fruit3 = c(rep(“apple”, 5), rep(“pear”, 5), rep(“banana”, 5))
# [1] NA

Works fine for nominal data. Let’s check for numerical data:

One mode
count1 = c(rep(1, 10), rep(2, 5), rep(3, 2))
# [1] 1

Two modes
count2 = c(rep(1, 5), rep(2, 5), rep(3, 2))
# [1] 1 2

No mode
count3 = c(rep(1, 5), rep(2, 5), rep(3, 5))
# [1] NA

To leave a comment for the author, please follow the link and comment on their blog: My R Nightmares. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)