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 61
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/na-if.R
\name{na_if}
\alias{na_if}
\title{Convert values to \code{NA}}
\usage{
na_if(x, y)
}
\arguments{
\item{x}{Vector to modify}
\item{y}{Value or vector to compare against. When \code{x} and \code{y} are equal, the
value in \code{x} will be replaced with \code{NA}.
\code{y} is \link[vctrs:theory-faq-coercion]{cast} to the type of \code{x} before
comparison.
\code{y} is \link[vctrs:theory-faq-recycling]{recycled} to the size of \code{x} before
comparison. This means that \code{y} can be a vector with the same size as \code{x},
but most of the time this will be a single value.}
}
\value{
A modified version of \code{x} that replaces any values that
are equal to \code{y} with \code{NA}.
}
\description{
This is a translation of the SQL command \code{NULLIF}. It is useful if you want
to convert an annoying value to \code{NA}.
}
\examples{
na_if(1:5, 5:1)
x <- c(1, -1, 0, 10)
100 / x
100 / na_if(x, 0)
y <- c("abc", "def", "", "ghi")
na_if(y, "")
# `na_if()` allows you to replace `NaN` with `NA`,
# even though `NaN == NaN` returns `NA`
z <- c(1, NaN, NA, 2, NaN)
na_if(z, NaN)
# `na_if()` is particularly useful inside `mutate()`,
# and is meant for use with vectors rather than entire data frames
starwars \%>\%
select(name, eye_color) \%>\%
mutate(eye_color = na_if(eye_color, "unknown"))
# `na_if()` can also be used with `mutate()` and `across()`
# to alter multiple columns
starwars \%>\%
mutate(across(where(is.character), ~na_if(., "unknown")))
}
\seealso{
\code{\link[=coalesce]{coalesce()}} to replace missing values with a specified
value.
\code{\link[tidyr:replace_na]{tidyr::replace_na()}} to replace \code{NA} with a value.
}
|