Returns the element that occurs most frequently in a vector.

calculate_mode(x, na.rm = TRUE)

Arguments

x

A vector of any atomic type (numeric, character, factor,).

na.rm

Logical; should missing values be ignored? Defaults to TRUE. If FALSE and x contains any NAs, the function returns NA.

Value

A single value giving the modal element of x. If two or more values are tied for the highest frequency, the first one encountered in x is returned.

Details

Internally the function:

  1. Optionally removes NAs (na.rm = TRUE).

  2. Builds a lookup table of unique values via unique(x).

  3. Counts the frequency of each unique value with tabulate(match(x, ux)).

  4. Returns the value with the maximum count.

Because it relies on base R functions, the implementation is vectorised and generally fast for typical data-frame column sizes.