Skip to content

This is a translation of the SQL command NULLIF. It is useful if you want to convert an annoying value to NA.

Usage

na_if(x, y)

Arguments

x

Vector to modify

y

Value to replace with NA

Value

A modified version of x that replaces any values that are equal to y with NA.

See also

coalesce() to replace missing values with a specified value.

tidyr::replace_na() to replace NA with a value.

recode() to more generally replace values.

Examples

na_if(1:5, 5:1)
#> [1]  1  2 NA  4  5

x <- c(1, -1, 0, 10)
100 / x
#> [1]  100 -100  Inf   10
100 / na_if(x, 0)
#> [1]  100 -100   NA   10

y <- c("abc", "def", "", "ghi")
na_if(y, "")
#> [1] "abc" "def" NA    "ghi"

# 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"))
#> # A tibble: 87 × 2
#>    name               eye_color
#>    <chr>              <chr>    
#>  1 Luke Skywalker     blue     
#>  2 C-3PO              yellow   
#>  3 R2-D2              red      
#>  4 Darth Vader        yellow   
#>  5 Leia Organa        brown    
#>  6 Owen Lars          blue     
#>  7 Beru Whitesun lars blue     
#>  8 R5-D4              red      
#>  9 Biggs Darklighter  brown    
#> 10 Obi-Wan Kenobi     blue-gray
#> # … with 77 more rows

# na_if() can also be used with mutate() and across()
# to mutate multiple columns
starwars %>%
   mutate(across(where(is.character), ~na_if(., "unknown")))
#> # A tibble: 87 × 14
#>    name  height  mass hair_…¹ skin_…² eye_c…³ birth…⁴ sex   gender homew…⁵
#>    <chr>  <int> <dbl> <chr>   <chr>   <chr>     <dbl> <chr> <chr>  <chr>  
#>  1 Luke…    172    77 blond   fair    blue       19   male  mascu… Tatooi…
#>  2 C-3PO    167    75 NA      gold    yellow    112   none  mascu… Tatooi…
#>  3 R2-D2     96    32 NA      white,… red        33   none  mascu… Naboo  
#>  4 Dart…    202   136 none    white   yellow     41.9 male  mascu… Tatooi…
#>  5 Leia…    150    49 brown   light   brown      19   fema… femin… Aldera…
#>  6 Owen…    178   120 brown,… light   blue       52   male  mascu… Tatooi…
#>  7 Beru…    165    75 brown   light   blue       47   fema… femin… Tatooi…
#>  8 R5-D4     97    32 NA      white,… red        NA   none  mascu… Tatooi…
#>  9 Bigg…    183    84 black   light   brown      24   male  mascu… Tatooi…
#> 10 Obi-…    182    77 auburn… fair    blue-g…    57   male  mascu… Stewjon
#> # … with 77 more rows, 4 more variables: species <chr>, films <list>,
#> #   vehicles <list>, starships <list>, and abbreviated variable names
#> #   ¹​hair_color, ²​skin_color, ³​eye_color, ⁴​birth_year, ⁵​homeworld