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.
Arguments
- condition
Logical vector
- true, false
Values to use for
TRUEandFALSEvalues ofcondition. They must be either the same length ascondition, or length 1. They must also be the same type:if_else()checks that they have the same type and same class. All other attributes are taken fromtrue.- missing
If not
NULL, will be used to replace missing values.
Value
Where condition is TRUE, the matching value from
true, where it's FALSE, the matching value from false,
otherwise NA.
Examples
x <- c(-5:5, NA)
if_else(x < 0, NA_integer_, x)
#> [1] NA NA NA NA NA 0 1 2 3 4 5 NA
if_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] 1 2 NA 1 NA NA NA 1 2 NA
if_else(x %in% c("a", "b", "c"), x, factor(NA))
#> [1] b c <NA> b <NA> <NA> <NA> b c <NA>
#> Levels: b c d e
# Attributes are taken from the `true` vector,
