在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?
当前回答
R有如此多的附加包,其中一些可以很好地提供数字列表/系列/向量的[统计]模式。
然而,R的标准库本身似乎没有这样一个内置的方法!解决这个问题的一种方法是使用一些像下面这样的结构(如果你经常使用…则将其转换为函数):
mySamples <- c(19, 4, 5, 7, 29, 19, 29, 13, 25, 19)
tabSmpl<-tabulate(mySamples)
SmplMode<-which(tabSmpl== max(tabSmpl))
if(sum(tabSmpl == max(tabSmpl))>1) SmplMode<-NA
> SmplMode
[1] 19
对于更大的示例列表,应该考虑使用一个临时变量max(tabSmpl)值(我不知道R会自动优化这个)
参考:参见KickStarting R课程中的“How about median and mode? 这似乎证实了(至少在写这节课的时候)R中没有模态函数(嗯…你会发现Mode()用于断言变量的类型)。
其他回答
另一个简单的选项是使用rle来给出所有按频率排序的值:
df = as.data.frame(unclass(rle(sort(mySamples))))
df = df[order(-df$lengths),]
head(df)
模式并不是在所有情况下都有用。所以函数应该处理这种情况。试试下面的函数。
Mode <- function(v) {
# checking unique numbers in the input
uniqv <- unique(v)
# frquency of most occured value in the input data
m1 <- max(tabulate(match(v, uniqv)))
n <- length(tabulate(match(v, uniqv)))
# if all elements are same
same_val_check <- all(diff(v) == 0)
if(same_val_check == F){
# frquency of second most occured value in the input data
m2 <- sort(tabulate(match(v, uniqv)),partial=n-1)[n-1]
if (m1 != m2) {
# Returning the most repeated value
mode <- uniqv[which.max(tabulate(match(v, uniqv)))]
} else{
mode <- "Two or more values have same frequency. So mode can't be calculated."
}
} else {
# if all elements are same
mode <- unique(v)
}
return(mode)
}
输出,
x1 <- c(1,2,3,3,3,4,5)
Mode(x1)
# [1] 3
x2 <- c(1,2,3,4,5)
Mode(x2)
# [1] "Two or more varibles have same frequency. So mode can't be calculated."
x3 <- c(1,1,2,3,3,4,5)
Mode(x3)
# [1] "Two or more values have same frequency. So mode can't be calculated."
我发现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)))])
}
可以尝试以下功能:
将数值转换为因子 使用summary()获取频率表 返回模式为频率最大的索引 转换因子回到数字,即使有超过1个模式,这个函数工作得很好!
mode <- function(x){
y <- as.factor(x)
freq <- summary(y)
mode <- names(freq)[freq[names(freq)] == max(freq)]
as.numeric(mode)
}
我将使用density()函数来确定一个(可能是连续的)分布的平滑最大值:
function(x) density(x, 2)$x[density(x, 2)$y == max(density(x, 2)$y)]
其中x是数据集合。注意调节平滑的密度函数的调节参数。