Vectorized choices

  • ifelse() is a vectorized version of if:
x <- 1:10
ifelse(x %% 5 == 0, "XXX", as.character(x))
#>  [1] "1"   "2"   "3"   "4"   "XXX" "6"   "7"   "8"   "9"   "XXX"

ifelse(x %% 2 == 0, "even", "odd")
#>  [1] "odd"  "even" "odd"  "even" "odd"  "even" "odd"  "even" "odd"  "even"
  • dplyr::if_else()

  • Book recommends only using ifelse() “only when the yes and no vectors are the same type as it is otherwise hard to predict the output type.”

  • dplyr::if_else() enforces this recommendation.

For example:

ifelse(c(TRUE,TRUE,FALSE),"a",3)
#> [1] "a" "a" "3"
dplyr::if_else(c(TRUE,TRUE,FALSE),"a",3)
#> Error in `dplyr::if_else()`:
#> ! `false` must be a character vector, not a double vector.