在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?
当前回答
下面的函数有三种形式:
method = "mode"[默认值]:计算单模态向量的模式,否则返回NA Method = "nmodes":计算vector中模式的个数 Method = "modes":列出单模态或多模态向量的所有模态
modeav <- function (x, method = "mode", na.rm = FALSE)
{
x <- unlist(x)
if (na.rm)
x <- x[!is.na(x)]
u <- unique(x)
n <- length(u)
#get frequencies of each of the unique values in the vector
frequencies <- rep(0, n)
for (i in seq_len(n)) {
if (is.na(u[i])) {
frequencies[i] <- sum(is.na(x))
}
else {
frequencies[i] <- sum(x == u[i], na.rm = TRUE)
}
}
#mode if a unimodal vector, else NA
if (method == "mode" | is.na(method) | method == "")
{return(ifelse(length(frequencies[frequencies==max(frequencies)])>1,NA,u[which.max(frequencies)]))}
#number of modes
if(method == "nmode" | method == "nmodes")
{return(length(frequencies[frequencies==max(frequencies)]))}
#list of all modes
if (method == "modes" | method == "modevalues")
{return(u[which(frequencies==max(frequencies), arr.ind = FALSE, useNames = FALSE)])}
#error trap the method
warning("Warning: method not recognised. Valid methods are 'mode' [default], 'nmodes' and 'modes'")
return()
}
其他回答
添加raster::modal()作为一个选项,不过请注意,raster是一个很大的包,如果不做地理空间方面的工作,可能不值得安装。
源代码可以从https://github.com/rspatial/raster/blob/master/src/modal.cpp和https://github.com/rspatial/raster/blob/master/R/modal.R中取出,放入个人R包中,供那些特别热衷的人使用。
可以尝试以下功能:
将数值转换为因子 使用summary()获取频率表 返回模式为频率最大的索引 转换因子回到数字,即使有超过1个模式,这个函数工作得很好!
mode <- function(x){
y <- as.factor(x)
freq <- summary(y)
mode <- names(freq)[freq[names(freq)] == max(freq)]
as.numeric(mode)
}
在我看来,如果一个集合有一个模式,那么它的元素就可以与自然数一一对应。因此,查找模式的问题简化为生成这样一个映射,查找映射值的模式,然后映射回集合中的一些项。(处理NA发生在映射阶段)。
我有一个直方图函数,它的原理类似。(本文代码中使用的特殊函数和操作符应在Shapiro和/或neatOveRse中定义。在此复制夏皮罗和奈尔斯的部分是经过允许的;复制的片段可根据本网站的条款使用。)直方图的伪代码是
.histogram <- function (i)
if (i %|% is.empty) integer() else
vapply2(i %|% max %|% seqN, `==` %<=% i %O% sum)
histogram <- function(i) i %|% rmna %|% .histogram
(特殊的二进制操作符完成管道、咖喱和组合)我还有一个maxloc函数,它与which类似。Max,但返回一个向量的所有绝对最大值。maxloc的R伪代码是
FUNloc <- function (FUN, x, na.rm=F)
which(x == list(identity, rmna)[[na.rm %|% index.b]](x) %|% FUN)
maxloc <- FUNloc %<=% max
minloc <- FUNloc %<=% min # I'M THROWING IN minloc TO EXPLAIN WHY I MADE FUNloc
Then
imode <- histogram %O% maxloc
and
x %|% map %|% imode %|% unmap
将计算任何集合的模式,只要定义了适当的映射-ping和取消映射-ping函数。
我还不能投票,但Rasmus Bååth的答案是我一直在寻找的。 但是,我将稍微修改一下,允许将分布限制在0到1之间。
estimate_mode <- function(x,from=min(x), to=max(x)) {
d <- density(x, from=from, to=to)
d$x[which.max(d$y)]
}
我们知道你可能根本不想约束你的分布,那么设置from=-"BIG NUMBER", to="BIG NUMBER"
另一个可能的解决方案:
Mode <- function(x) {
if (is.numeric(x)) {
x_table <- table(x)
return(as.numeric(names(x_table)[which.max(x_table)]))
}
}
用法:
set.seed(100)
v <- sample(x = 1:100, size = 1000000, replace = TRUE)
system.time(Mode(v))
输出:
user system elapsed
0.32 0.00 0.31