如何使用R语言显示众数以及众数出现的频率?

3

我有一个数据集,其中列是投票,行是议员。我希望计算一致性指数,因此需要众数的频率。

一列看起来像这样

V1
1
3
2
1
1
2
1

我知道以下代码可以显示模式:
getmode <- function(v) {
  uniqv <- unique(v)
  uniqv[which.max(tabulate(match(v, uniqv)))]
}

我知道R语言可以显示数值的频率。

a <- table(df$V1)
print(a)

有没有办法让R显示众数(在我的例子中是1)的频率,比如在我的例子中是4?
2个回答

1

你只需要这样做

a <- table(df$V1)
max(a)

或者使用您的getmode函数。
sum(df$V1 == getmode(df$V1))

1

您可以通过以下方式集成您的getmode()函数:

getmode <- function(v) {
  uniqv <- unique(v)
  mode <- uniqv[which.max(tabulate(match(v, uniqv)))]
  freq <- sum(v==mode)                      # here you count the values = to mode
  dats <- data.frame(                       # you can put in a data.frame
                      mode = (mode),        # mode
                      freq = (freq)         # frequency
                     )
  print(dats)                               # here you print the result               
  }

# let's try it
getmode(V1)
  mode freq
1    1    4

带有数据的:

V1 <- c(1,3,2,1,1,2,1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接