在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?
当前回答
这里有另一个解决方案:
freq <- tapply(mySamples,mySamples,length)
#or freq <- table(mySamples)
as.numeric(names(freq)[which.max(freq)])
其他回答
对此有多种解决方案。我检查了第一个,然后写了我自己的。把它贴在这里,如果它能帮助到任何人:
Mode <- function(x){
y <- data.frame(table(x))
y[y$Freq == max(y$Freq),1]
}
让我们用几个例子来测试一下。我正在取虹膜数据集。让我们用数值数据进行测试
> Mode(iris$Sepal.Length)
[1] 5
你可以验证这是正确的。
现在虹膜数据集中唯一的非数字字段(Species)没有模式。让我们用我们自己的例子进行测试
> test <- c("red","red","green","blue","red")
> Mode(test)
[1] red
EDIT
正如注释中提到的,用户可能希望保留输入类型。在这种情况下,mode函数可以修改为:
Mode <- function(x){
y <- data.frame(table(x))
z <- y[y$Freq == max(y$Freq),1]
as(as.character(z),class(x))
}
函数的最后一行只是将最终的模式值强制为原始输入的类型。
抱歉,我可能把它理解得太简单了,但这不是可以工作的吗?(我的机器上的1E6值在1.3秒内):
t0 <- Sys.time()
summary(as.factor(round(rnorm(1e6), 2)))[1]
Sys.time()-t0
你只需要用你的向量替换“round(rnorm(1e6),2)”。
我将使用density()函数来确定一个(可能是连续的)分布的平滑最大值:
function(x) density(x, 2)$x[density(x, 2)$y == max(density(x, 2)$y)]
其中x是数据集合。注意调节平滑的密度函数的调节参数。
基于@Chris的函数来计算模态或相关指标,但是使用Ken Williams的方法来计算频率。这个方法修复了根本没有模式(所有元素频率相等)的情况,并提供了一些更易读的方法名。
Mode <- function(x, method = "one", na.rm = FALSE) {
x <- unlist(x)
if (na.rm) {
x <- x[!is.na(x)]
}
# Get unique values
ux <- unique(x)
n <- length(ux)
# Get frequencies of all unique values
frequencies <- tabulate(match(x, ux))
modes <- frequencies == max(frequencies)
# Determine number of modes
nmodes <- sum(modes)
nmodes <- ifelse(nmodes==n, 0L, nmodes)
if (method %in% c("one", "mode", "") | is.na(method)) {
# Return NA if not exactly one mode, else return the mode
if (nmodes != 1) {
return(NA)
} else {
return(ux[which(modes)])
}
} else if (method %in% c("n", "nmodes")) {
# Return the number of modes
return(nmodes)
} else if (method %in% c("all", "modes")) {
# Return NA if no modes exist, else return all modes
if (nmodes > 0) {
return(ux[which(modes)])
} else {
return(NA)
}
}
warning("Warning: method not recognised. Valid methods are 'one'/'mode' [default], 'n'/'nmodes' and 'all'/'modes'")
}
由于它使用Ken的方法来计算频率,性能也得到了优化,使用AkselA的帖子,我对之前的一些答案进行了基准测试,以显示我的函数在性能上是如何接近Ken的,各种输出选项的条件只导致很小的开销:
下面是可以用来找到R中矢量变量的模式的代码。
a <- table([vector])
names(a[a==max(a)])