Compared to the base ifelse()
, this function is more strict.
It checks that true
and false
are the same type. This
strictness makes the output type more predictable, and makes it somewhat
faster.
if_else(condition, true, false, missing = NULL)
condition | Logical vector |
---|---|
true, false | Values to use for |
missing | If not |
Where condition
is TRUE
, the matching value from
true
, where it's FALSE
, the matching value from false
,
otherwise NA
.
#> [1] NA NA NA NA NA 0 1 2 3 4 5 NAif_else(x < 0, "negative", "positive", "missing")#> [1] "negative" "negative" "negative" "negative" "negative" "positive" #> [7] "positive" "positive" "positive" "positive" "positive" "missing"# Unlike ifelse, if_else preserves types x <- factor(sample(letters[1:5], 10, replace = TRUE)) ifelse(x %in% c("a", "b", "c"), x, factor(NA))#> [1] NA 3 NA 3 NA 1 1 NA 2 NA#> [1] <NA> c <NA> c <NA> a a <NA> b <NA> #> Levels: a b c d e# Attributes are taken from the `true` vector,