在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?


当前回答

效果很好

> a<-c(1,1,2,2,3,3,4,4,5)
> names(table(a))[table(a)==max(table(a))]

其他回答

这里有另一个解决方案:

freq <- tapply(mySamples,mySamples,length)
#or freq <- table(mySamples)
as.numeric(names(freq)[which.max(freq)])

我发现Ken Williams上面的帖子很棒,我添加了几行来解释NA值,并使其成为一个函数。

Mode <- function(x, na.rm = FALSE) {
  if(na.rm){
    x = x[!is.na(x)]
  }

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

我将使用density()函数来确定一个(可能是连续的)分布的平滑最大值:

function(x) density(x, 2)$x[density(x, 2)$y == max(density(x, 2)$y)]

其中x是数据集合。注意调节平滑的密度函数的调节参数。

另一个可能的解决方案:

Mode <- function(x) {
    if (is.numeric(x)) {
        x_table <- table(x)
        return(as.numeric(names(x_table)[which.max(x_table)]))
    }
}

用法:

set.seed(100)
v <- sample(x = 1:100, size = 1000000, replace = TRUE)
system.time(Mode(v))

输出:

   user  system elapsed 
   0.32    0.00    0.31 

这是我的数据。返回完整表的逐行模式的表解决方案。我用它来推断行类。它负责data中新的set()函数。桌子,应该很快。虽然它不管理NA,但可以通过查看本页上的众多其他解决方案添加。

majorityVote <- function(mat_classes) {
  #mat_classes = dt.pour.centroids_num
  dt.modes <- data.table(mode = integer(nrow(mat_classes)))
  for (i in 1:nrow(mat_classes)) {
    cur.row <- mat_classes[i]
    cur.mode <- which.max(table(t(cur.row)))
    set(dt.modes, i=i, j="mode", value = cur.mode)
  }

  return(dt.modes)
}

可能的用法:

newClass <- majorityVote(my.dt)  # just a new vector with all the modes