How to find mode(s) of a vector in R?

Just like mean and median there is no in-built function in R to find the mode.

We can make use of the following user created function for this purpose

> Modes <- function(x) {
   ux <- unique(x)
   tab <- tabulate(match(x, ux))
   ux[tab == max(tab)]


> x<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,6)
> Modes(x)
[1] 4

We have created a function called modes because a data can have more than one mode as shown below −

> y<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,3)
> Modes(y)
[1] 3 4

Updated on: 06-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started