if_else {poorman} | R Documentation |
Vectorised if
Description
This is a wrapper around ifelse()
which checks that true
and false
are of the same type, making the output more
predictable.
Usage
if_else(condition, true, false, missing = NULL)
Arguments
condition |
A |
true , false |
Values to use for |
missing |
If not |
Value
A vector the same length as condition
with values for TRUE
and FALSE
replaced by those specified in
true
and false
, respectively.
Examples
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))
# Attributes are taken from the `true` vector
if_else(x %in% c("a", "b", "c"), x, factor(NA))
[Package poorman version 0.2.7 Index]