base::ifelse
returns NA
to the logical type NA
. It makes data manipulation problematic when we generate a new variable by ifelse
from the existing varialbes with NA
s. The following example gives an idea how the class of ifelse
resutls changes.
test_fn <- function(x){
ifelse(x > 0,
"Positive",
"Not positive")
}
class(test_fn(1))
## [1] "character"
class(test_fn(NA))
## [1] "logical"
To avoid this problem, we have two solutions:
- coerce the class explicitly
- Use
dplyr::if_else
test_fn2 <- function(x){
dplyr::if_else(x > 0,
"Positive",
"Not positive")
}
class(test_fn2(1))
## [1] "character"
class(test_fn2(NA))
## [1] "character"