Coercing the class of ifelse results

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 NAs. 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:

  1. coerce the class explicitly
  2. 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"
comments powered by Disqus