forked from tidyverse/dplyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathna_if.R
29 lines (28 loc) · 759 Bytes
/
na_if.R
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
#' Convert values to NA.
#'
#' This is a translation of the SQL command \code{NULL_IF}. It is useful
#' if you want to convert an annoying value to \code{NA}.
#'
#' @param x Vector to modify
#' @param y Value to replace with NA
#' @return A modified version of \code{x} that replaces any values that
#' are equal to \code{y} with NA.
#' @seealso \code{\link{coalesce}()} to replace missing values with a specified
#' value.
#' @export
#' @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 <- function(x, y) {
if (length(y) != length(x) && length(y) != 1) {
stop("`y` must be length 1 or same length as `x`", call. = FALSE)
}
x[x == y] <- NA
x
}