How to find the statistical mode?

前端 未结 30 1673
时光取名叫无心
时光取名叫无心 2020-11-21 07:00

In R, mean() and median() are standard functions which do what you\'d expect. mode() tells you the internal storage mode of the objec

30条回答
  •  长发绾君心
    2020-11-21 07:44

    Another possible solution:

    Mode <- function(x) {
        if (is.numeric(x)) {
            x_table <- table(x)
            return(as.numeric(names(x_table)[which.max(x_table)]))
        }
    }
    

    Usage:

    set.seed(100)
    v <- sample(x = 1:100, size = 1000000, replace = TRUE)
    system.time(Mode(v))
    

    Output:

       user  system elapsed 
       0.32    0.00    0.31 
    

提交回复
热议问题