Good way to find the majority in an R vector?

advertisements

In a vector in R, if I have a data likes:

1 1 2 1 1 3 3 1 1

In this case, 1 is majority.

Of course, I can loop through a list and count manually, but is there a better way in R to find what is the major value in a vector?


You can use table

x <- c(1,1,2,1,1,3,3,1,1)
which.max(table(x))
# 1
# 1

Maybe, something like this would be more helpful.

names(which.max(table(x)))
# "1"


Another option is using count function from plyr package

library(plyr)
df <- count(x)
df[which.max(df$freq),1]
# [1] 1