如何显示模式以及模式出现的频率?

时间:2018-12-18 20:48:34

标签: r

我有一个数据集,其中选票为列,议员为行。我想计算一个协议索引,因此需要该模式的频率。

一列看起来像像这样

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)

在我的示例1中,R是否有办法采取这种模式,并在我的示例4中向我展示它的频率?

2 个答案:

答案 0 :(得分:1)

你可以做

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

或使用您的getmode函数

sum(df$V1 == getmode(df$V1))

答案 1 :(得分: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)