https://github.com/hadley/dplyr
Raw File
Tip revision: 5d74be59a690f07734dad6effff0c1f7950c7fc3 authored by Romain Francois on 19 February 2020, 10:16:54 UTC
+ bench-distinct.R
Tip revision: 5d74be5
na_if.Rd
% 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 NA}
\usage{
na_if(x, y)
}
\arguments{
\item{x}{Vector to modify}

\item{y}{Value to replace with NA}
}
\value{
A modified version of \code{x} that replaces any values that
are equal to \code{y} with 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 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 scoped variants of mutate
# like mutate_if to mutate multiple columns
starwars \%>\%
  mutate_if(is.character, list(~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.

\code{\link[=recode]{recode()}} to more generally replace values.
}
back to top