Consider these factor objects:
x <- factor(c(1,2,2,4,5), 1:5, labels = c('Ja', 'Nein', '', 'Weiß nicht', 'Keine Antwort'))
y <- factor(c(1:5), 1:5, labels = c('Ja', 'Nein', '', 'Weiß nicht', 'Keine Antwort'))
> table(x)
x
Ja Nein Weiß nicht Keine Antwort
1 2 0 1 1
> table(y)
y
Ja Nein Weiß nicht Keine Antwort
1 1 1 1 1
I'm trying to use dplyr::recode to recode various variables. I can't get the function to recode an empty string level to NA and to drop the specific factor level.
Using
dplyr::recode(x,
"Weiß nicht" = NA_character_,
"Weiß nicht " = NA_character_,
"Keine Antwort" = NA_character_,
"Keine Antwort " = NA_character_,
"k.A." = NA_character_,
"Keine Angabe" = NA_character_,
"0" = NA_character_,
"" = NA_character_)
will result in an error message (Error: attempt to use zero-length variable name). Using
z <- dplyr::recode(na_if(x, ""),
"Weiß nicht" = NA_character_,
"Weiß nicht " = NA_character_,
"Keine Antwort" = NA_character_,
"Keine Antwort " = NA_character_,
"k.A." = NA_character_,
"Keine Angabe" = NA_character_,
"0" = NA_character_)
as described in Recode character vector with some empty strings does not get rid of the empty string level:
> table(z)
z
Ja Nein
1 2 0
> levels(z)
[1] "Ja" "Nein" ""
Additionally, I can't simply use droplevels because I want to use the function on variables which may have empty categories I need to retain.
A solution would need to provide to things:
- Recode any occurence of
""toNA. - Drop level
""fromfactorvariable, even when it is unused (as inx), without dropping every unused level.