|
15 | 15 | #' but most of the time this will be a single value. |
16 | 16 | #' @return A modified version of `x` that replaces any values that |
17 | 17 | #' are equal to `y` with `NA`. |
18 | | -#' @seealso [coalesce()] to replace missing values with a specified |
19 | | -#' value. |
20 | 18 | #' |
21 | | -#' [tidyr::replace_na()] to replace `NA` with a value. |
| 19 | +#' @seealso |
| 20 | +#' |
| 21 | +#' - [coalesce()] to replace `NA`s with the first non-missing value. |
| 22 | +#' |
| 23 | +#' - [replace_values()] for making arbitrary replacements by value. |
| 24 | +#' |
| 25 | +#' - [replace_when()] for making arbitrary replacements using logical |
| 26 | +#' conditions. |
| 27 | +#' |
22 | 28 | #' @export |
23 | 29 | #' @examples |
24 | | -#' na_if(1:5, 5:1) |
| 30 | +#' # `na_if()` is useful for replacing a single problematic value with `NA` |
| 31 | +#' na_if(c(-99, 1, 4, 3, -99, 5), -99) |
| 32 | +#' na_if(c("abc", "def", "", "ghi"), "") |
| 33 | +#' |
| 34 | +#' # You can use it to standardize `NaN`s to `NA` |
| 35 | +#' na_if(c(1, NaN, NA, 2, NaN), NaN) |
| 36 | +#' |
| 37 | +#' # Because `na_if()` is an R translation of SQL's `NULLIF` command, |
| 38 | +#' # it compares `x` and `y` element by element. Where `x` and `y` are |
| 39 | +#' # equal, the value in `x` is replaced with an `NA`. |
| 40 | +#' na_if( |
| 41 | +#' x = c(1, 2, 5, 5, 6), |
| 42 | +#' y = c(0, 2, 3, 5, 4) |
| 43 | +#' ) |
| 44 | +#' |
| 45 | +#' # If you have multiple problematic values that you'd like to replace with |
| 46 | +#' # `NA`, then `replace_values()` is a better choice than `na_if()` |
| 47 | +#' x <- c(-99, 1, 4, 0, -99, 5, -1, 0, 5) |
| 48 | +#' replace_values(x, c(0, -1, -99) ~ NA) |
25 | 49 | #' |
26 | | -#' x <- c(1, -1, 0, 10) |
27 | | -#' 100 / x |
28 | | -#' 100 / na_if(x, 0) |
| 50 | +#' # You'd have to nest `na_if()`s to achieve this |
| 51 | +#' try(na_if(x, c(0, -1, -99))) |
| 52 | +#' na_if(na_if(na_if(x, 0), -1), -99) |
29 | 53 | #' |
30 | | -#' y <- c("abc", "def", "", "ghi") |
31 | | -#' na_if(y, "") |
| 54 | +#' # If you'd like to replace values that match a logical condition with `NA`, |
| 55 | +#' # use `replace_when()` |
| 56 | +#' replace_when(x, x < 0 ~ NA) |
32 | 57 | #' |
33 | | -#' # `na_if()` allows you to replace `NaN` with `NA`, |
34 | | -#' # even though `NaN == NaN` returns `NA` |
35 | | -#' z <- c(1, NaN, NA, 2, NaN) |
36 | | -#' na_if(z, NaN) |
| 58 | +#' # If you'd like to replace `NA` with some other value, use `replace_values()` |
| 59 | +#' x <- c(NA, 5, 2, NA, 0, 3) |
| 60 | +#' replace_values(x, NA ~ 0) |
37 | 61 | #' |
38 | | -#' # `na_if()` is particularly useful inside `mutate()`, |
39 | | -#' # and is meant for use with vectors rather than entire data frames |
| 62 | +#' # `na_if()` is particularly useful inside `mutate()` |
40 | 63 | #' starwars |> |
41 | 64 | #' select(name, eye_color) |> |
42 | 65 | #' mutate(eye_color = na_if(eye_color, "unknown")) |
|
0 commit comments