How to find the statistical mode?

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

    This builds on jprockbelly's answer, by adding a speed up for very short vectors. This is useful when applying mode to a data.frame or datatable with lots of small groups:

    Mode <- function(x) {
       if ( length(x) <= 2 ) return(x[1])
       if ( anyNA(x) ) x = x[!is.na(x)]
       ux <- unique(x)
       ux[which.max(tabulate(match(x, ux)))]
    }
    

提交回复
热议问题