| vec_if_else {vctrs} | R Documentation |
Vectorized if-else
Description
vec_if_else() is a vectorized if-else. Compared to the base R
equivalent, ifelse(), this function allows you to handle missing values in
the condition with missing and always takes true, false, and
missing into account when determining what the output type should be.
Usage
vec_if_else(
condition,
true,
false,
...,
missing = NULL,
ptype = NULL,
condition_arg = "condition",
true_arg = "true",
false_arg = "false",
missing_arg = "missing",
error_call = current_env()
)
Arguments
condition |
A logical vector. |
true, false |
Vectors to use for Both
|
... |
These dots are for future extensions and must be empty. |
missing |
If not |
ptype |
An optional prototype declaring the desired output type. If
supplied, this overrides the common type of |
condition_arg, true_arg, false_arg, missing_arg |
Argument names used in error messages. |
error_call |
The execution environment of a currently
running function, e.g. |
Value
A vector with the same size as condition and the same type as the common
type of true, false, and missing.
Where condition is TRUE, the matching values from true, where it is
FALSE, the matching values from false, and where it is NA, the matching
values from missing, if provided, otherwise a missing value will be used.
Examples
x <- c(-5:5, NA)
vec_if_else(x < 0, NA, x)
# Explicitly handle `NA` values in the `condition` with `missing`
vec_if_else(x < 0, "negative", "positive", missing = "missing")
# Unlike `ifelse()`, `vec_if_else()` preserves types
x <- factor(sample(letters[1:5], 10, replace = TRUE))
ifelse(x %in% c("a", "b", "c"), x, NA)
vec_if_else(x %in% c("a", "b", "c"), x, NA)
# `vec_if_else()` also works with data frames
condition <- c(TRUE, FALSE, NA, TRUE)
true <- data_frame(x = 1:4, y = 5:8)
false <- data_frame(x = 9:12, y = 13:16)
vec_if_else(condition, true, false)