Convert vector to factor based on threshold of number of unique levels
Source:R/ds2dd_detailed.R
var2fct.Rd
This is a wrapper of forcats::as_factor, which sorts numeric vectors before factoring, but levels character vectors in order of appearance.
Examples
sample(seq_len(4), 20, TRUE) |>
var2fct(6) |>
summary()
#> 1 2 3 4
#> 7 3 6 4
sample(letters, 20) |>
var2fct(6) |>
summary()
#> Length Class Mode
#> 20 character character
sample(letters[1:4], 20, TRUE) |> var2fct(6)
#> Warning: invalid roman numerals: a a b b b a b b a
#> [1] a c c a b c d c c b d b a d d c b d b a
#> Levels: a c b d