Skip to content
Prev 44758 / 398502 Next

Computing the mode

Aurora Torrente wrote:
There are several possibilities, e.g for *discrete* data:

  x <- floor(runif(100, min=10, max=20)) # some discrete data

Half a year ago it was proposed to use e.g.:

  x[rev(order(table(x)))[1]]

another possibility is:

  f <- table(x)
  as.numeric(names(f[max(f)==f])) # extracts mode(s) from vector names

For *continuous data* you can use class frequencies (from hist) together
with an interpolation formula. Another approximative solution uses
kernel density estimates (the density function):

  x <- rnorm(100, mean=5, sd=1)  # generate some data
  hist(x, prob=TRUE)
  dens <- density(x)
  lines(dens)
  dens$x[dens$y == max(dens$y)] # gives the mode


The precision depends on the parameters of the density() function. If
the distribution is multi-modal, I use a small function peaks() to
extract several maxima (a generalized version of the one in R-news 
2003/3 p. 9).

Thomas P.