Description Usage Arguments Value See Also Examples
This is a translation of the SQL command NULL_IF
. It is useful
if you want to convert an annoying value to NA
.
1 | na_if(x, y)
|
x |
Vector to modify |
y |
Value to replace with NA |
A modified version of x
that replaces any values that
are equal to y
with NA.
coalesce()
to replace missing values with a specified
value.
tidyr::replace_na()
to replace NA
with a value.
recode()
to more generally replace values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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, funs(na_if(., "unknown")))
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.