How to find the statistical mode?

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

    Mode can't be useful in every situations. So the function should address this situation. Try the following function.

    Mode <- function(v) {
      # checking unique numbers in the input
      uniqv <- unique(v)
      # frquency of most occured value in the input data
      m1 <- max(tabulate(match(v, uniqv)))
      n <- length(tabulate(match(v, uniqv)))
      # if all elements are same
      same_val_check <- all(diff(v) == 0)
      if(same_val_check == F){
        # frquency of second most occured value in the input data
        m2 <- sort(tabulate(match(v, uniqv)),partial=n-1)[n-1]
        if (m1 != m2) {
          # Returning the most repeated value
          mode <- uniqv[which.max(tabulate(match(v, uniqv)))]
        } else{
          mode <- "Two or more values have same frequency. So mode can't be calculated."
        }
      } else {
        # if all elements are same
        mode <- unique(v)
      }
      return(mode)
    }
    

    Output,

    x1 <- c(1,2,3,3,3,4,5)
    Mode(x1)
    # [1] 3
    
    x2 <- c(1,2,3,4,5)
    Mode(x2)
    # [1] "Two or more varibles have same frequency. So mode can't be calculated."
    
    x3 <- c(1,1,2,3,3,4,5)
    Mode(x3)
    # [1] "Two or more values have same frequency. So mode can't be calculated."
    

提交回复
热议问题