1

table()我可以使用函数获得分类变量的水平和频率。但是我需要稍后将最频繁的级别输入到计算中。我怎样才能做到这一点?

例如,我想从分类变量 a 中获取“191”。

> table(a)
a
  19   71   98  139  146  185  191 
 305   75  179  744    1 1980 6760
4

3 回答 3

5
a <- sample(x = c(19,   71,   98,  139,  146,  185,  191), size = 1000, replace = TRUE)
tt <- table(a)
names(tt[which.max(tt)])
于 2013-08-25T21:08:54.940 回答
1
ll<-data.frame(table(a))
ll[which.max(ll$Freq),]

来自 mtcars 数据的示例:

ll<-data.frame(table(mtcars$cyl))
 ll
  Var1 Freq
1    4   11
2    6    7
3    8   14

ll[which.max(ll$Freq),]
  Var1 Freq
3    8   14
于 2013-08-25T21:05:12.230 回答
1

这在某种程度上与模式问题有关,您可以在其中找到许多其他解决方案来获得最常见的级别。我收集了一些单线解决方案,并在有多个最常见级别时显示解决方案。

#Create Dataset
x <- c("a","a","b","c","c")

#Some ways to get the FIRST most frequent level: "a"
names(which.max(table(x)))
names(sort(-table(x)))[1]
names(sort(-table(x))[1])

#Some ways to get ALL most frequent levels: "a" "c"
names(which(max(table(x))==table(x)))
names(table(x))[table(x)==max(table(x))]
names(table(x)[table(x)==max(table(x))])
#or the same but replace "table(x)" with "z"
z <- table(x)
names(which(max(z)==z))
names(z)[z==max(z)]
names(z[z==max(z)])
于 2019-03-20T16:13:02.920 回答