Skip to contents

mode_single() returns the only mode in a vector. If there are multiple modes, it returns NA by default.

Usage

mode_single(
  x,
  na.rm = FALSE,
  na.rm.amount = 0,
  accept = FALSE,
  multiple = c("NA", "min", "max", "mean", "median", "first", "last", "random")
)

Arguments

x

A vector to search for its mode.

na.rm

Logical. Should missing values in x be removed before computation proceeds? Default is FALSE.

na.rm.amount

Numeric. Alternative to na.rm that only removes a specified number of missing values. Default is 0.

accept

Logical. Should the minimum set of modes be accepted to check for a single mode? If FALSE (the default), insists on the complete set and returns NA if it can't be determined.

multiple

String or integer (length 1), or a function. What to do if x has multiple modes? The default returns NA. All other options rely on the modal values: "min", "max", "mean", "median", "first", "last", and "random". Alternatively, multiple can be an index number, or a function that summarizes the modes. See details.

Value

The only mode (most frequent value) in x. If it can't be determined because of missing values, NA is returned instead. If there are multiple modes, NA is returned by default (multiple = "NA").

Details

If accept is FALSE (the default), the set of modes is obtained via mode_all() instead of mode_possible_min(). Set it to TRUE to avoid returning NA when some, though not all modes are known. The purpose of the default is to insist on a single mode.

If x is a string vector and multiple is "min" or "max", the mode is selected lexically, just like min(letters) returns "a". The "mean" and "median" options return NA with a warning. For factors, "min", "max", and "median" are errors, but "mean" returns NA with a warning. These are inconsistencies in base R.

The multiple options "first" and "last" always select the mode that appears first or last in x. Index numbers, like multiple = 2, allow you to select more flexibly. If multiple is a function, its output must be length 1.

See also

Examples

# `8` is the only mode:
mode_single(c(8, 8, 9))
#> [1] 8

# With more than one mode, the function
# returns `NA`:
mode_single(c(1, 2, 3, 3, 4, 4))
#> [1] NA

# Can't determine the modes here --
# `9` might be another mode:
mode_single(c(8, 8, 9, NA))
#> [1] NA

# Accept `8` anyways if it's
# sufficient to just have any mode:
mode_single(c(8, 8, 9, NA), accept = TRUE)
#> [1] 8

# `1` is the most frequent value,
# no matter what `NA` stands for:
mode_single(c(1, 1, 1, 2, NA))
#> [1] 1

# Ignore `NA`s with `na.rm = TRUE`
# (there should be good reasons for this!):
mode_single(c(8, 8, 9, NA), na.rm = TRUE)
#> [1] 8