File: if_else.Rd

package info (click to toggle)
r-cran-dplyr 1.1.4-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,292 kB
  • sloc: cpp: 1,403; sh: 17; makefile: 7
file content (60 lines) | stat: -rw-r--r-- 2,428 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
% 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 = NULL)
}
\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}{An optional size declaring the desired output size. If supplied,
this overrides the size of \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")
}