% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/if-else.R
\name{if_else}
\alias{if_else}
\title{Vectorised if-else}
\usage{
if_else(
  condition,
  true,
  false,
  missing = NULL,
  ...,
  ptype = NULL,
  size = deprecated()
)
}
\arguments{
\item{condition}{A logical vector}

\item{true, false}{Vectors to use for \code{TRUE} and \code{FALSE} values of
\code{condition}.

Both \code{true} and \code{false} will be \link[vctrs:theory-faq-recycling]{recycled}
to the size of \code{condition}.

\code{true}, \code{false}, and \code{missing} (if used) will be cast to their common type.}

\item{missing}{If not \code{NULL}, will be used as the value for \code{NA} values of
\code{condition}. Follows the same size and type rules as \code{true} and \code{false}.}

\item{...}{These dots are for future extensions and must be empty.}

\item{ptype}{An optional prototype declaring the desired output type. If
supplied, this overrides the common type of \code{true}, \code{false}, and \code{missing}.}

\item{size}{\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#deprecated}{\figure{lifecycle-deprecated.svg}{options: alt='[Deprecated]'}}}{\strong{[Deprecated]}}

Output size is always taken from \code{condition}.}
}
\value{
A vector with the same size as \code{condition} and the same type as the common
type of \code{true}, \code{false}, and \code{missing}.

Where \code{condition} is \code{TRUE}, the matching values from \code{true}, where it is
\code{FALSE}, the matching values from \code{false}, and where it is \code{NA}, the matching
values from \code{missing}, if provided, otherwise a missing value will be used.
}
\description{
\code{if_else()} is a vectorized \link[=if]{if-else}. Compared to the base R equivalent,
\code{\link[=ifelse]{ifelse()}}, this function allows you to handle missing values in the
\code{condition} with \code{missing} and always takes \code{true}, \code{false}, and \code{missing}
into account when determining what the output type should be.
}
\examples{
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")
}
\seealso{
\code{\link[vctrs:vec_if_else]{vctrs::vec_if_else()}}
}
