使用starts_with()将NA替换为0

Dan*_*Dan 7 r na tidyverse

我正在尝试替换我的一组特定列的NA值tibble.列都以相同的前缀开头,所以我想知道是否有一种简洁的方法来使用包中的starts_with()函数来dplyr允许我这样做.

我在SO上看到了其他几个问题,但是它们都需要使用特定的列名或位置.我真的想要懒惰,不想定义所有列,只是前缀.

replace_na()tidyr包中尝试了这个功能无济于事.我知道我的代码对于作业是错误的,但我的词汇量不够大,不知道在哪里看.

Reprex:

library(tidyverse)

tbl1 <- tibble(
 id = c(1, 2, 3),
 num_a = c(1, NA, 4),
 num_b = c(NA, 99, 100),
 col_c = c("d", "e", NA)
)

replace_na(tbl1, list(starts_with("num_") = 0)))
Run Code Online (Sandbox Code Playgroud)

aos*_*ith 7

mutate_atif_else(或case_when)一起使用怎么样?如果要将NA感兴趣的列中的所有列替换为0,则此方法有效.

mutate_at(tbl1, vars( starts_with("num_") ), 
          funs( if_else( is.na(.), 0, .) ) )

# A tibble: 3 x 4
     id num_a num_b col_c
  <dbl> <dbl> <dbl> <chr>
1     1     1     0     d
2     2     0    99     e
3     3     4   100  <NA>
Run Code Online (Sandbox Code Playgroud)

请注意,starts_with其他选择助手返回一个整数向量,给出匹配变量的位置. 在我通常使用它们之外的情况下尝试使用它时,我总是要记住这一点.

  • 两个微小的变化 - 不知道是否更好:`mutate_at(tbd1,vars(starts_with('num_')),funs(替换(.,is.na(.),0)))`和`mutate_at (tbd1,vars(starts_with('num_')),funs(replace_na(.,0)))` (3认同)