if_else | R Documentation |
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.
if_else(condition, true, false, missing = NULL, ..., ptype = NULL, size = NULL)
condition |
A logical vector |
true, false |
Vectors to use for Both
|
missing |
If not |
... |
These dots are for future extensions and must be empty. |
ptype |
An optional prototype declaring the desired output type. If
supplied, this overrides the common type of |
size |
An optional size declaring the desired output size. If supplied,
this overrides the size of |
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.
x <- c(-5:5, NA)
if_else(x < 0, NA, x)
# Explicitly handle `NA` values in the `condition` with `missing`
if_else(x < 0, "negative", "positive", missing = "missing")
# Unlike `ifelse()`, `if_else()` preserves types
x <- factor(sample(letters[1:5], 10, replace = TRUE))
ifelse(x %in% c("a", "b", "c"), x, NA)
if_else(x %in% c("a", "b", "c"), x, NA)
# `if_else()` is often useful for creating new columns inside of `mutate()`
starwars %>%
mutate(category = if_else(height < 100, "short", "tall"), .keep = "used")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.