在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?
当前回答
抱歉,我可能把它理解得太简单了,但这不是可以工作的吗?(我的机器上的1E6值在1.3秒内):
t0 <- Sys.time()
summary(as.factor(round(rnorm(1e6), 2)))[1]
Sys.time()-t0
你只需要用你的向量替换“round(rnorm(1e6),2)”。
其他回答
这个黑客应该工作良好。给你的值以及模式的计数:
Mode <- function(x){
a = table(x) # x is a vector
return(a[which.max(a)])
}
假设你的观测值是来自实数的类,当你的观测值是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"
另一个简单的选项是使用rle来给出所有按频率排序的值:
df = as.data.frame(unclass(rle(sort(mySamples))))
df = df[order(-df$lengths),]
head(df)
计算模式大多是在有因素变量的情况下才可以使用
labels(table(HouseVotes84$V1)[as.numeric(labels(max(table(HouseVotes84$V1))))])
HouseVotes84是在“mlbench”包中可用的数据集。
它会给出最大标签值。它更容易由内置函数本身使用,而无需编写函数。
如果你问R中的内置函数,也许你可以在软件包pracma中找到它。在这个包中,有一个叫做Mode的函数。