在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?
当前回答
对此有多种解决方案。我检查了第一个,然后写了我自己的。把它贴在这里,如果它能帮助到任何人:
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))
}
函数的最后一行只是将最终的模式值强制为原始输入的类型。
其他回答
我还不能投票,但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"
下面的函数有三种形式:
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()
}
如果你问R中的内置函数,也许你可以在软件包pracma中找到它。在这个包中,有一个叫做Mode的函数。
对此有多种解决方案。我检查了第一个,然后写了我自己的。把它贴在这里,如果它能帮助到任何人:
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))
}
函数的最后一行只是将最终的模式值强制为原始输入的类型。
下面是一个查找模式的函数:
mode <- function(x) {
unique_val <- unique(x)
counts <- vector()
for (i in 1:length(unique_val)) {
counts[i] <- length(which(x==unique_val[i]))
}
position <- c(which(counts==max(counts)))
if (mean(counts)==max(counts))
mode_x <- 'Mode does not exist'
else
mode_x <- unique_val[position]
return(mode_x)
}