Mode: Mode of a vector (numeric/character/factor)

View source: R/vector_tools.R

ModeR Documentation

Mode of a vector (numeric/character/factor)

Description

There is no built-in function to find the mode of something. This function can find the mode of a numeric, character, or factor vector. By default it will return multiple values in a multi-modal dataset, but there are several methods of tie-breaking included.

Usage

Mode(x, break_ties = "no", na.rm = FALSE, ties = NULL, mean = NULL)

Arguments

x

(Char/Numeric/Factor) A vector.

break_ties

(Character) If more than one mode is found, how should the tie be broken?

  • "no" or FALSE: Return a vector of all of the modes that were found.

  • "random": Randomly choose one of the modes to return.

  • "mean": Return the average of all of the modes (for numeric vectors).

  • "first": Return the first mode found.

  • "last": Return the last mode found.

  • "median": Return the median value of all of the modes.

  • "median l" or "median r": Return the mode to the left or right of the median.

  • "NA": Return NA. Useful if you only want one clear winner.

na.rm

(Logical) If TRUE, NAs will be silently removed.

ties

Deprecated (2019-02-26). Use break_ties instead.

mean

Deprecated (2019-02-26). Use break_ties instead.

Details

If all values are unique, it will return all of the values unless you choose to break the tie.

Value

A vector of the mode value(s).

Authors

Source

https://stackoverflow.com/a/8189441/5578429

Examples

vec <- c(1, 2, 3, 4, 4, 4, 3, 3, NA, NA, NA)

Mode(vec, break_ties = "no")
#> [1]  3  4 NA

Mode(vec, break_ties = "no", na.rm = TRUE)
#> [1] 3 4

Mode(vec, break_ties = "mean", na.rm = FALSE)
#> [1] NA

Mode(vec, break_ties = "mean", na.rm = TRUE)
#> [1] 3.5

Mode(vec, break_ties = "median", na.rm = TRUE)
#> [1] 3

Mode(letters[1:4], break_ties = "no")
#> [1] "a" "b" "c" "d"

Mode(letters[1:4], break_ties = "median l")
#> "b"

Mode(letters[1:4], break_ties = "median r")
#> "c"

Mode(letters[1:4], break_ties = "random")
#> [1] "a"


DesiQuintans/desiderata documentation built on April 9, 2023, 5:43 a.m.