使用mutate_if和replace_na将数字列中的NA替换为非空值

20

我希望使用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
2个回答

39
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  

1
太棒了!我一直在寻找一个优雅的解决方案,我认为这是一个非常普遍的问题,但只找到了更加令人困惑的答案。这就是解决方案!谢谢 - Bernd V.
is_fun_list(.funs) 中出现错误: 找不到对象 'replace_na'。 - stallingOne
dplyr中的mutate_if函数已被暂停,并被across替代。我已在另一个答案中添加了解决方案。 - Jochem

7

另一个答案提到的基于 mutate_if 的解决方案是基于 dplyr 中的一个暂停函数。建议的替代方法是使用 across() 函数。以下是使用该函数的解决方案:

df %>% 
  mutate(
    across(where(is.numeric), ~replace_na(.x, 0))
  )

# A tibble: 3 × 3
  first second third
  <chr>  <dbl> <dbl>
1 a          0    10
2 NA         2     0
3 b          0     0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接