tidyverse / forcats

🐈🐈🐈🐈: tools for working with categorical variables (factors)
https://forcats.tidyverse.org/
Other
554 stars 126 forks source link

preserve subclasses as well as attrs in `refactor()` #367

Open khusmann opened 3 months ago

khusmann commented 3 months ago

As @TimTaylor first pointed out in #83, refactor() overwrites the class with the reset result of factor. This affects a bunch of methods downstream of refactor() like lvls_expand(), lvls_reorder(), fct_lump_n(), etc.

Because refactor() sometimes needs to set ordered in the class list, it's not as simple as ignoring the class of the new factor. Instead, if ordered is being toggled off, it drops "ordered" from the original class list; if it's being toggled on, it adds "ordered" to the original class list; if nothing is changed it uses the original class list. As a result, all the subclasses in the original factor propagate to the result, instead of getting lost.

The tests in lvls-test.R demonstrate this functionality.

Cheers!