Skip to contents

Returns the most frequent value in x. Used as the built-in default for imputeMissingCovariates()'s categoricalFn argument, and exposed publicly so callers can plug it into their own workflows or compose it with other rules.

Usage

imputeMode(x, missingToken = NULL)

Arguments

x

A non-empty atomic vector (character, factor, numeric, integer, or logical). Length-0 input errors.

missingToken

Optional atomic vector of sentinel values to exclude from the candidate set (compared after as.character() on both sides). Default NULL means no values are excluded.

Value

A length-1 value of the same atomic type as x (factor for factor input).

Details

Properties:

  • Deterministic tie-break. When two or more values tie for the highest frequency, the one that appears first in x wins. This makes the result stable across runs and independent of locale- sensitive ordering inside table().

  • Factor-preserving. If x is a factor, the return value is a factor with the same levels(x). Plain character / numeric vectors return a length-1 value of the same atomic type.

  • NA-tolerant. NA entries are ignored when computing the mode. If every entry is NA the function errors.

  • Optional token avoidance. When missingToken is supplied, values matching any element of it are excluded from the candidate set. imputeMissingCovariates() masks the input pool up-front so this is normally a no-op there; the parameter is useful when calling imputeMode() standalone on a raw vector that may still contain sentinels.

Examples

imputeMode(c("M", "F", "M", "F"))                       # "M" (ties: first wins)
#> [1] "M"
imputeMode(factor(c("M", "F", "M"), levels = c("F","M"))) # factor "M"
#> [1] M
#> Levels: F M
imputeMode(c(70, 70, 65, -99), missingToken = -99)        # 70
#> [1] 70