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


当前回答

这是我的数据。返回完整表的逐行模式的表解决方案。我用它来推断行类。它负责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

其他回答

抱歉,我可能把它理解得太简单了,但这不是可以工作的吗?(我的机器上的1E6值在1.3秒内):

t0 <- Sys.time()
summary(as.factor(round(rnorm(1e6), 2)))[1]
Sys.time()-t0

你只需要用你的向量替换“round(rnorm(1e6),2)”。

估计来自连续单变量分布(例如正态分布)的数字向量的模式的一种快速而肮脏的方法是定义并使用以下函数:

estimate_mode <- function(x) {
  d <- density(x)
  d$x[which.max(d$y)]
}

然后得到模态估计:

x <- c(5.8, 5.6, 6.2, 4.1, 4.9, 2.4, 3.9, 1.8, 5.7, 3.2)
estimate_mode(x)
## 5.439788

假设你的观测值是来自实数的类,当你的观测值是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"

可以尝试以下功能:

将数值转换为因子 使用summary()获取频率表 返回模式为频率最大的索引 转换因子回到数字,即使有超过1个模式,这个函数工作得很好!

mode <- function(x){
  y <- as.factor(x)
  freq <- summary(y)
  mode <- names(freq)[freq[names(freq)] == max(freq)]
  as.numeric(mode)
}

这是我的数据。返回完整表的逐行模式的表解决方案。我用它来推断行类。它负责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