Convert vector to factor based on threshold of number of unique levels
This is a wrapper of forcats::as_factor, which sorts numeric vectors before factoring, but levels character vectors in order of appearance.
var2fct(data, unique.n)
data
: vector or data.frame columnunique.n
: threshold to convert class to factorvector
sample(seq_len(4), 20, TRUE) |> var2fct(6) |> summary() sample(letters, 20) |> var2fct(6) |> summary() sample(letters[1:4], 20, TRUE) |> var2fct(6)
Useful links