在R中,mean()和median()是标准函数,它们执行您所期望的功能。Mode()告诉您对象的内部存储模式,而不是参数中出现次数最多的值。但是是否存在一个标准库函数来实现向量(或列表)的统计模式?


当前回答

对Ken Williams的回答做了一个小修改,增加了可选的params na。Rm和return_multiple。

与依赖names()的答案不同,此答案在返回值中维护x的数据类型。

stat_mode <- function(x, return_multiple = TRUE, na.rm = FALSE) {
  if(na.rm){
    x <- na.omit(x)
  }
  ux <- unique(x)
  freq <- tabulate(match(x, ux))
  mode_loc <- if(return_multiple) which(freq==max(freq)) else which.max(freq)
  return(ux[mode_loc])
}

要显示它与可选参数一起工作并维护数据类型:

foo <- c(2L, 2L, 3L, 4L, 4L, 5L, NA, NA)
bar <- c('mouse','mouse','dog','cat','cat','bird',NA,NA)

str(stat_mode(foo)) # int [1:3] 2 4 NA
str(stat_mode(bar)) # chr [1:3] "mouse" "cat" NA
str(stat_mode(bar, na.rm=T)) # chr [1:2] "mouse" "cat"
str(stat_mode(bar, return_mult=F, na.rm=T)) # chr "mouse"

感谢@Frank的简化。

其他回答

为了生成模式,我写了下面的代码。

MODE <- function(dataframe){
    DF <- as.data.frame(dataframe)

    MODE2 <- function(x){      
        if (is.numeric(x) == FALSE){
            df <- as.data.frame(table(x))  
            df <- df[order(df$Freq), ]         
            m <- max(df$Freq)        
            MODE1 <- as.vector(as.character(subset(df, Freq == m)[, 1]))

            if (sum(df$Freq)/length(df$Freq)==1){
                warning("No Mode: Frequency of all values is 1", call. = FALSE)
            }else{
                return(MODE1)
            }

        }else{ 
            df <- as.data.frame(table(x))  
            df <- df[order(df$Freq), ]         
            m <- max(df$Freq)        
            MODE1 <- as.vector(as.numeric(as.character(subset(df, Freq == m)[, 1])))

            if (sum(df$Freq)/length(df$Freq)==1){
                warning("No Mode: Frequency of all values is 1", call. = FALSE)
            }else{
                return(MODE1)
            }
        }
    }

    return(as.vector(lapply(DF, MODE2)))
}

让我们试试吧:

MODE(mtcars)
MODE(CO2)
MODE(ToothGrowth)
MODE(InsectSprays)

我浏览了所有这些选项,开始想知道它们的相对特性和性能,所以我做了一些测试。如果其他人也好奇,我在这里分享我的结果。

我不想为这里发布的所有函数而烦恼,我选择了一个基于一些标准的示例:函数应该对字符、因子、逻辑和数字向量都有效,它应该适当地处理na和其他有问题的值,输出应该是“合理的”,即没有数字作为字符或其他类似的愚蠢行为。

我还添加了一个我自己的函数,它是基于与chrispy相同的想法,除了适应更一般的用途:

library(magrittr)

Aksel <- function(x, freq=FALSE) {
    z <- 2
    if (freq) z <- 1:2
    run <- x %>% as.vector %>% sort %>% rle %>% unclass %>% data.frame
    colnames(run) <- c("freq", "value")
    run[which(run$freq==max(run$freq)), z] %>% as.vector   
}

set.seed(2)

F <- sample(c("yes", "no", "maybe", NA), 10, replace=TRUE) %>% factor
Aksel(F)

# [1] maybe yes  

C <- sample(c("Steve", "Jane", "Jonas", "Petra"), 20, replace=TRUE)
Aksel(C, freq=TRUE)

# freq value
#    7 Steve

最后,我通过微基准测试在两组测试数据上运行了五个函数。函数名指的是它们各自的作者:

Chris的函数被设置为method="modes"和na。rm=TRUE默认值,以使其更具可比性,但除此之外,这里使用的函数是由它们的作者提供的。

In matter of speed alone Kens version wins handily, but it is also the only one of these that will only report one mode, no matter how many there really are. As is often the case, there's a trade-off between speed and versatility. In method="mode", Chris' version will return a value iff there is one mode, else NA. I think that's a nice touch. I also think it's interesting how some of the functions are affected by an increased number of unique values, while others aren't nearly as much. I haven't studied the code in detail to figure out why that is, apart from eliminating logical/numeric as a the cause.

我还不能投票,但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){
  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))
}

函数的最后一行只是将最终的模式值强制为原始输入的类型。

有一个包谦和提供单变量单模态(有时是多模态)数据的模态估计和通常概率分布的模态值。

mySamples <- c(19, 4, 5, 7, 29, 19, 29, 13, 25, 19)

library(modeest)
mlv(mySamples, method = "mfv")

Mode (most likely value): 19 
Bickel's modal skewness: -0.1 
Call: mlv.default(x = mySamples, method = "mfv")

欲了解更多信息,请参阅本页

你也可以在CRAN任务视图:概率分布中寻找“模式估计”。已经提出了两个新的一揽子计划。