Learn R Programming

forcats (version 0.0.0.9000)

fct_lump: Lump together least/most common levels into "other".

Description

Lump together least/most common levels into "other".

Usage

fct_lump(f, n, prop, other_level = "Other")

Arguments

f
A factor.
n, prop
If both n and prop are missing, fct_lump lumps together the least frequent levels into "other", while ensuring that "other" is still the smallest level. It's particularly useful in conjunction with fct_inorder().

Positive n preserves the most common n values. Negative n preserves the least common -n values. It there are ties, you will get at least abs(n) values.

Positive prop, preserves values that appear at least prop of the time. Negative prop, preserves values that appear at most -prop of the time.

other_level
Value of level used for "other" values. Always placed at end of levels.

Examples

Run this code
x <- factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))
x %>% table()
x %>% fct_lump() %>% table()
x %>% fct_lump() %>% fct_inorder() %>% table()

x <- factor(letters[rpois(100, 5)])
x
table(x)
table(fct_lump(x))

# Use positive values to collapse the rarest
fct_lump(x, n = 3)
fct_lump(x, prop = 0.1)

# Use negative values to collapse the most common
fct_lump(x, n = -3)
fct_lump(x, prop = -0.1)

Run the code above in your browser using DataLab