感觉这应该可以使用mutate_at
or 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
但实际上我们开始时没有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
我可以保存这个子集,然后使用 bind_rows,但我想desired
在一个管道中创建列。同样,这感觉应该是可行的,mutate_at
或者mutate(across(...))
我还没有成功。
问题:如何desired
使用 dplyr 在一个管道中创建指标列?
你可以用
library(dplyr)
df %>%
mutate(desired = +if_any(contains("test"), is.na))
要得到
# 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句