% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/if-else.R
\name{vec_if_else}
\alias{vec_if_else}
\title{Vectorized if-else}
\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{
\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[=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{...}{These dots are for future extensions and must be empty.}

\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{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{condition_arg, true_arg, false_arg, missing_arg}{Argument names used in
error messages.}

\item{error_call}{The execution environment of a currently
running function, e.g. \code{caller_env()}. The function will be
mentioned in error messages as the source of the error. See the
\code{call} argument of \code{\link[rlang:abort]{abort()}} for more information.}
}
\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{vec_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)
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)
}
