Computes the statistical mode of a set of values. The mode is defined as the most frequent value, i.e. the value that is most likely to be sampled.
Usage
stat_mode(x, type = c("one", "all", "n"), rm_na = FALSE)
Arguments
- x
An R object.
- type
What the function should calculate.
"one"
: Return the mode ofx
. If multiple modes or no mode at all exists,NA
is returned."all"
: Return all modes ofx
. If none exists (e.g. because all values ofx
are distinct),NA
is returned."n"
: Return the number of modes ofx
.
- rm_na
Ignore missing values in
x
. A logical scalar.
Value
If type = "n"
, the number of modes in x
(an integer). Otherwise, the mode(s) of x
or NA
if none exist(s) (same type as x
).
See also
The package modeest for more powerful mode estimation functions.
Other statistical computing / numeric functions:
round_to()
,
safe_max()
,
safe_min()
,
safe_seq_len()
Examples
pal::stat_mode(c(rep(3L, times = 3), 1:9))
#> [1] 3
pal::stat_mode(c(1.5, 4, 9.9))
#> [1] NA
# if no mode exists, `NA` (of the same type as x) is returned
pal::stat_mode(letters)
#> [1] NA
pal::stat_mode(c(letters, "a"))
#> [1] "a"
# if multiple modes exist, `NA` is returned by default
pal::stat_mode(c(letters, "a", "b"))
#> [1] NA
# set `type = "all"` to return all modes instead
pal::stat_mode(c(letters, "a", "b"),
type = "all")
#> [1] "a" "b"
# `NA` is treated as any other value by default
pal::stat_mode(c(letters, "a", NA_character_, NA_character_),
type = "all")
#> [1] "a" NA
# set `rm_na = TRUE` to ignore `NA` values
pal::stat_mode(c(letters, "a", NA_character_, NA_character_),
type = "all",
rm_na = TRUE)
#> [1] "a"