forcats icon indicating copy to clipboard operation
forcats copied to clipboard

fct_na_value_to_level() adds a level for NA value even if it is not need

Open LukaszDerylo opened this issue 2 years ago • 1 comments

Imagine a factor without NAs on which you call fct_na_value_to_level().

Formely, fct_explicit_na() did absolutely nothing in such case:

letters[1:3] %>% factor %>% fct_explicit_na('x')
[1] a b c
Levels: a b c

Now, fct_na_value_to_level() adds a level for NA value even if it is not need:

letters[1:3] %>% factor %>% fct_na_value_to_level('x')
[1] a b c
Levels: a b c x

So, simple replacement (fct_na_value_to_level for fct_explicit_na) breaks existing code sometimes.

Ideally, fct_na_value_to_level() could behave just like fct_explicit_na() did. Or, at least warning message should inform somehow about above case.

LukaszDerylo avatar Feb 24 '23 09:02 LukaszDerylo

Reprex

library(forcats)
letters[1:3] %>% factor %>% fct_na_value_to_level('x')
#> [1] a b c
#> Levels: a b c x

Created on 2023-02-27 with reprex v2.0.2

hadley avatar Feb 27 '23 19:02 hadley