在R中的向量中找到多数的好方法?

mam*_*atv 1 r

在R中的向量中,如果我有数据喜欢:

1 1 2 1 1 3 3 1 1

在这种情况下,1是多数.

当然,我可以循环遍历列表并手动计数,但是在R中有更好的方法来查找向量中的主要值吗?

Ron*_*hah 6

您可以使用 table

x <- c(1,1,2,1,1,3,3,1,1)
which.max(table(x))
# 1 
# 1
Run Code Online (Sandbox Code Playgroud)

也许,这样的事情会更有帮助.

names(which.max(table(x)))
# "1"
Run Code Online (Sandbox Code Playgroud)

另一个选择是使用包中的count函数plyr

library(plyr)
df <- count(x)
df[which.max(df$freq),1]
# [1] 1
Run Code Online (Sandbox Code Playgroud)