【问题标题】:Replace NA on numeric columns with mutate_if and replace_na用 mutate_if 和 replace_na 替换数字列上的 NA
【发布时间】:2018-08-26 18:45:03
【问题描述】:

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

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

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:
    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  
    

    【讨论】:

    • 太棒了!我为此寻找了一个优雅的解决方案,虽然这是一个很常见的问题,但只找到了更令人困惑的答案。这就是解决方案!谢谢
    • is_fun_list(.funs) 中的错误:找不到对象“replace_na”
    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2014-03-20
    • 2018-10-14
    • 2022-06-16
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多