获取数据集模式的前三个值

Getting the first three values of a dataset's mode

我正在尝试使用 R 学习模式。我在网上一些代码,我对其进行了一些修改:

getmode <- function(v) {
  uniqv <- unique(v)
  first <- uniqv[which.max(tabulate(match(v, uniqv)))]
  mode <- first
  # cancel "first" occurrences
  second<- uniqv[which.max(tabulate(match(v, uniqv)))]
  mode <- second
  # cancel "second" occurrences
  third <- uniqv[which.max(tabulate(match(v, uniqv)))]
  # cancel "third" occurrences
  mode <- third
  print(mode)
  }

它returns只有第一个值(最大值),但我想打印前三个值。我的想法是取消第一个最频繁值 (#) 的所有出现,重新使用以前的代码并获得第二个最频繁的值,取消它并再次重复例程以获得第三个。这看起来很容易,但我无法让它工作。有人可以帮助我吗?

否则,您是否知道任何其他方法来获取我的数据集每个属性的前 3 个最大值?

Summary() 有效,但不关注模式,也不只关注我的某些属性(它为所有属性而不是我想要的属性提供价值)。

一种类似于您所想的方法。

使用 here 中的模式功能。

Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

我们可以在删除之前的模式值后调用Mode函数三次。

x <- rep(1:5, c(6, 5, 1, 2, 9))
three_modes <- numeric(3)

for(i in seq_along(three_modes)) {
  three_modes[i] <- Mode(x)
   x <- x[x!=three_modes[i]]
}

three_modes
#[1] 5 1 2

您可以将 3 替换为任何您喜欢的数字以获得顶级 n 模式。