How to find the statistical mode?

前端 未结 30 2165
时光取名叫无心
时光取名叫无心 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:39

    There are multiple solutions provided for this one. I checked the first one and after that wrote my own. Posting it here if it helps anyone:

    Mode <- function(x){
      y <- data.frame(table(x))
      y[y$Freq == max(y$Freq),1]
    }
    

    Lets test it with a few example. I am taking the iris data set. Lets test with numeric data

    > Mode(iris$Sepal.Length)
    [1] 5
    

    which you can verify is correct.

    Now the only non numeric field in the iris dataset(Species) does not have a mode. Let's test with our own example

    > test <- c("red","red","green","blue","red")
    > Mode(test)
    [1] red
    

    EDIT

    As mentioned in the comments, user might want to preserve the input type. In which case the mode function can be modified to:

    Mode <- function(x){
      y <- data.frame(table(x))
      z <- y[y$Freq == max(y$Freq),1]
      as(as.character(z),class(x))
    }
    

    The last line of the function simply coerces the final mode value to the type of the original input.

提交回复
热议问题