Request for Mode (Most Common) function

Can anyone explain why:

  1. There is no mode (as in most common) function in either base R or tidyverse?
  2. 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(!]
  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 {

You've kind of answered it yourself.

mode does not necessarily produce a unique result, so deciding between ties is somewhat arbitrary. You may have seen this already, but it gives a few custom function options, as well as some used in packages:
r - How to find the statistical mode? - Stack Overflow

Maybe mode is not exactly the right name, but the functionality (single value representing most common value with a tiebreak method) must be useful enough. And a well-optimised version even better.

The data I work with needs an aggregate function to supplement the usual sum/min/max - I am surprised that is a rare requirement.

My function may well have come from this stackoverflow thread

This should be optimised:
Fast (Grouped, Weighted) Statistical Mode for Matrix-Like Objects — fmode • collapse (

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.