如何使用 dplyr 根据列的子集中的任何一个是否为 NA 创建新列

Jas*_*lns 3 r dplyr

感觉这应该可以使用mutate_ator mutate(across(...)),但我不明白什么......

假设我们有以下内容。我包含了所需的输出desired,它是一个指标列,基于包含单词“test”的任何列是否具有NA值:

library(tidyverse)

df <- tibble::tribble(
  ~id,    ~name, ~test_col, ~is_test, ~another_test, ~desired,
   1L, "mickey",        NA,      13L,           12L,       1L,
   2L, "donald",       19L,       NA,            NA,       1L,
   3L,  "daisy",       15L,      20L,           20L,       0L,
   4L,  "goofy",       18L,      14L,           10L,       0L,
   5L,  "pluto",       16L,      10L,            NA,       1L,
   6L, "minnie",       19L,      15L,           16L,       0L
  )

df
#> # A tibble: 6 x 6
#>      id name   test_col is_test another_test desired
#>   <int> <chr>     <int>   <int>        <int>   <int>
#> 1     1 mickey       NA      13           12       1
#> 2     2 donald       19      NA           NA       1
#> 3     3 daisy        15      20           20       0
#> 4     4 goofy        18      14           10       0
#> 5     5 pluto        16      10           NA       1
#> 6     6 minnie       19      15           16       0
Run Code Online (Sandbox Code Playgroud)

但实际上我们开始时没有desired列:df_start <- df %>% select(-desired)

我可以成功地使用fiter_at仅获取包含“测试”的一列或多列的观察结果NA

df_start %>% 
  filter_at(vars(contains("test")), any_vars(is.na(.)))
#> # A tibble: 3 x 5
#>      id name   test_col is_test another_test
#>   <int> <chr>     <int>   <int>        <int>
#> 1     1 mickey       NA      13           12
#> 2     2 donald       19      NA           NA
#> 3     5 pluto        16      10           NA
Run Code Online (Sandbox Code Playgroud)

我可以保存这个子集,然后使用 bind_rows,但我想desired在一个管道中创建列。同样,这感觉应该是可行的,mutate_at或者mutate(across(...))我还没有成功。

问题:如何desired使用 dplyr 在一个管道中创建指标列?

reprex 包( v2.0.0 )在 2021-08-29 创建的示例

Mar*_*Gal 6

你可以用

library(dplyr)

df %>% 
  mutate(desired = +if_any(contains("test"), is.na))
Run Code Online (Sandbox Code Playgroud)

要得到

# A tibble: 6 x 6
     id name   test_col is_test another_test desired
  <int> <chr>     <int>   <int>        <int>   <int>
1     1 mickey       NA      13           12       1
2     2 donald       19      NA           NA       1
3     3 daisy        15      20           20       0
4     4 goofy        18      14           10       0
5     5 pluto        16      10           NA       1
6     6 minnie       19      15           16       0
Run Code Online (Sandbox Code Playgroud)