使用mutate_if和replace_na替换数字列上的NA

时间:2018-03-17 21:28:38

标签: r tidyverse

如果可能,我想使用mutate_ifreplace_na的某些变体替换数字列中的NAs,但无法弄清楚语法。

df <-tibble(
    first = c("a", NA, "b"),
    second = c(NA, 2, NA),
    third = c(10, NA, NA)
  )

#> # A tibble: 3 x 3
#>   first second third
#>   <chr>  <dbl> <dbl>
#> 1 a      NA     10.0
#> 2 <NA>    2.00  NA  
#> 3 b      NA     NA

最终结果应为:

#> # A tibble: 3 x 3
#>   first second third
#>   <chr>  <dbl> <dbl>
#> 1 a       0     10.0
#> 2 <NA>    2.00   0  
#> 3 b       0      0

我的尝试看起来像:

df %>% mutate_if(is.numeric , replace_na(., 0) )
#>Error: is_list(replace) is not TRUE

1 个答案:

答案 0 :(得分:10)

df %>% mutate_if(is.numeric , replace_na, replace = 0)

# A tibble: 3 x 3
#  first second third
#  <chr>  <dbl> <dbl>
#1 a       0     10.0
#2 NA      2.00   0  
#3 b       0      0