Can anyone explain why:
- There is no mode (as in most common) function in either base R or tidyverse?
- How to request one?
I find it very strange that neither base R nor tidyverse have a versatile mode function - apart from the fact that base R used the name mode for something else.
I want a function which will take any class, ignore NA and return a single value, with max used as tiebreak (and then an equivalent function with min as tiebreak)
I use the following but doubt its efficiency
It's a shame that max of 2 logicals returns an integer.
I did look at fmode from the package collapse - but that does not perform the correct max on character input.
# MostCommon is most often used in summarise to get the single most common non-empty value in a vector (ie grouping in group_by)
# where there is a tie, it returns max value in sort order
MostCommon <- function(x) {
ux <- unique(x)
uxnotna <- ux[which(!is.na(ux))]
if(length(uxnotna) > 0) {
tab <- tabulate(match(x, uxnotna))
candidates <- uxnotna[tab == max(tab)]
if (is.logical(x)) {
any(candidates) # return TRUE if any true. max returns an integer
} else {
max(candidates) # return highest (ie max) value
}
} else {
x[NA_integer_]
}
}