Compared to the base
ifelse(), this function is more strict.
It checks that
false are the same type. This
strictness makes the output type more predictable, and makes it somewhat
if_else(condition, true, false, missing = NULL)
- true, false
Values to use for
condition. They must be either the same length as
condition, or length 1. They must also be the same type:
if_elsechecks that they have the same type and same class. All other attributes are taken from
NULL, will be used to replace missing values.
TRUE, the matching value from
true, where it's
FALSE, the matching value from
x <- c(-5:5, NA) if_else(x < 0, NA_integer_, x) if_else(x < 0, "negative", "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)) if_else(x %in% c("a", "b", "c"), x, factor(NA)) # Attributes are taken from the `true` vector,