在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?
当前回答
我发现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)))])
}
其他回答
这个黑客应该工作良好。给你的值以及模式的计数:
Mode <- function(x){
a = table(x) # x is a vector
return(a[which.max(a)])
}
在r邮件列表中发现了这个,希望对你有帮助。我也是这么想的。您将希望table()数据,排序,然后选择第一个名称。这有点粗俗,但应该有用。
names(sort(-table(x)))[1]
计算模式大多是在有因素变量的情况下才可以使用
labels(table(HouseVotes84$V1)[as.numeric(labels(max(table(HouseVotes84$V1))))])
HouseVotes84是在“mlbench”包中可用的数据集。
它会给出最大标签值。它更容易由内置函数本身使用,而无需编写函数。
这是我的数据。返回完整表的逐行模式的表解决方案。我用它来推断行类。它负责data中新的set()函数。桌子,应该很快。虽然它不管理NA,但可以通过查看本页上的众多其他解决方案添加。
majorityVote <- function(mat_classes) {
#mat_classes = dt.pour.centroids_num
dt.modes <- data.table(mode = integer(nrow(mat_classes)))
for (i in 1:nrow(mat_classes)) {
cur.row <- mat_classes[i]
cur.mode <- which.max(table(t(cur.row)))
set(dt.modes, i=i, j="mode", value = cur.mode)
}
return(dt.modes)
}
可能的用法:
newClass <- majorityVote(my.dt) # just a new vector with all the modes
基于@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的,各种输出选项的条件只导致很小的开销: