I encountered an unexpected output when I used %in% in a condition whilst recoding a categorical variable.
When an element of a vector on the left is NA, the condition evaluates as FALSE, whilst I expected it to be NA.
The expected behaviour is the more verbose statement with two == conditions separated by an |
dt <- data.frame(colour = c("red", "orange", "blue", NA))
# Expected
dt$is_warm1 <- ifelse(dt$colour == "red" | dt$colour == "orange", TRUE, FALSE)
# Unexpected
dt$is_warm2 <- ifelse(dt$colour %in% c("red", "orange"), TRUE, FALSE)
dt
#> colour is_warm1 is_warm2
#> 1 red TRUE TRUE
#> 2 orange TRUE TRUE
#> 3 blue FALSE FALSE
#> 4 <NA> NA FALSE
This is quite unhelpful when recoding categorical variables because it silently fills missing values. Why does this happen, and are there any alternatives that don't involve listing all the == conditions? (Imagine that colour contains thirty possible levels).