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


当前回答

下面是一个查找模式的函数:

mode <- function(x) {
  unique_val <- unique(x)
  counts <- vector()
  for (i in 1:length(unique_val)) {
    counts[i] <- length(which(x==unique_val[i]))
  }
  position <- c(which(counts==max(counts)))
  if (mean(counts)==max(counts)) 
    mode_x <- 'Mode does not exist'
  else 
    mode_x <- unique_val[position]
  return(mode_x)
}

其他回答

计算模式大多是在有因素变量的情况下才可以使用

labels(table(HouseVotes84$V1)[as.numeric(labels(max(table(HouseVotes84$V1))))])

HouseVotes84是在“mlbench”包中可用的数据集。

它会给出最大标签值。它更容易由内置函数本身使用,而无需编写函数。

还有一个解决方案,适用于数字和字符/因子数据:

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

在我的小机器上,它可以在大约半秒内生成并找到一个10m整数向量的模式。

如果您的数据集可能有多种模式,上述解决方案采用与which相同的方法。Max,并返回模式集中第一个出现的值。要返回所有模式,使用这个变体(来自评论中的@digEmAll):

Modes <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux))
  ux[tab == max(tab)]
}

这建立在jprockbelly的答案上,通过对非常短的向量增加速度。这在将mode应用到data.frame或包含很多小组的数据表时非常有用:

Mode <- function(x) {
   if ( length(x) <= 2 ) return(x[1])
   if ( anyNA(x) ) x = x[!is.na(x)]
   ux <- unique(x)
   ux[which.max(tabulate(match(x, ux)))]
}

假设你的观测值是来自实数的类,当你的观测值是2,2,3,3时,你期望模态为2.5,然后你可以用mode = l1 + I * (f1-f0) / (2f1 -f0 - f2)来估计模态,其中l1..最频繁类的下限,f1..最频繁类的频率,f0..在最频繁类之前的类的频率,f2..在最频繁类之后的类的频率,i..分类间隔,如在1,2,3中给出:

#Small Example
x <- c(2,2,3,3) #Observations
i <- 1          #Class interval

z <- hist(x, breaks = seq(min(x)-1.5*i, max(x)+1.5*i, i), plot=F) #Calculate frequency of classes
mf <- which.max(z$counts)   #index of most frequent class
zc <- z$counts
z$breaks[mf] + i * (zc[mf] - zc[mf-1]) / (2*zc[mf] - zc[mf-1] - zc[mf+1])  #gives you the mode of 2.5


#Larger Example
set.seed(0)
i <- 5          #Class interval
x <- round(rnorm(100,mean=100,sd=10)/i)*i #Observations

z <- hist(x, breaks = seq(min(x)-1.5*i, max(x)+1.5*i, i), plot=F)
mf <- which.max(z$counts)
zc <- z$counts
z$breaks[mf] + i * (zc[mf] - zc[mf-1]) / (2*zc[mf] - zc[mf-1] - zc[mf+1])  #gives you the mode of 99.5

如果你想要最频繁的级别,并且你有多个最频繁的级别,你可以得到所有的级别,例如:

x <- c(2,2,3,5,5)
names(which(max(table(x))==table(x)))
#"2" "5"

如果你问R中的内置函数,也许你可以在软件包pracma中找到它。在这个包中,有一个叫做Mode的函数。