當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R dplyr na_if 將值轉換為 NA

這是 SQL 命令 NULLIF 的翻譯。如果您想將煩人的值轉換為 NA ,它會很有用。

用法

na_if(x, y)

參數

x

要修改的向量

y

要比較的值或向量。當 xy 相等時,x 中的值將替換為 NA

在比較之前,y 將轉換為 x 的類型。

yrecycled 與比較前x 的大小。這意味著 y 可以是與 x 大小相同的向量,但大多數時候這將是單個值。

x 的修改版本,將等於 y 的任何值替換為 NA

也可以看看

coalesce() 用指定值替換缺失值。

tidyr::replace_na()NA 替換為值。

例子

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()` allows you to replace `NaN` with `NA`,
# even though `NaN == NaN` returns `NA`
z <- c(1, NaN, NA, 2, NaN)
na_if(z, NaN)
#> [1]  1 NA NA  2 NA

# `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
#> # ℹ 77 more rows

# `na_if()` can also be used with `mutate()` and `across()`
# to alter multiple columns
starwars %>%
   mutate(across(where(is.character), ~na_if(., "unknown")))
#> # A tibble: 87 × 14
#>    name      height  mass hair_color skin_color eye_color birth_year sex  
#>    <chr>      <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr>
#>  1 Luke Sky…    172    77 blond      fair       blue            19   male 
#>  2 C-3PO        167    75 NA         gold       yellow         112   none 
#>  3 R2-D2         96    32 NA         white, bl… red             33   none 
#>  4 Darth Va…    202   136 none       white      yellow          41.9 male 
#>  5 Leia Org…    150    49 brown      light      brown           19   fema…
#>  6 Owen Lars    178   120 brown, gr… light      blue            52   male 
#>  7 Beru Whi…    165    75 brown      light      blue            47   fema…
#>  8 R5-D4         97    32 NA         white, red red             NA   none 
#>  9 Biggs Da…    183    84 black      light      brown           24   male 
#> 10 Obi-Wan …    182    77 auburn, w… fair       blue-gray       57   male 
#> # ℹ 77 more rows
#> # ℹ 6 more variables: gender <chr>, homeworld <chr>, species <chr>,
#> #   films <list>, vehicles <list>, starships <list>
源代碼:R/na-if.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Convert values to NA。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。