Vectorized choices
ifelse()
is a vectorized version ofif
:
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: