【发布时间】:2021-08-29 17:43:27
【问题描述】:
感觉 mutate_at 或 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(...)) 实现,但我还没有成功。
问题:如何使用 dplyr 在一个管道中创建指标列desired?
reprex package (v2.0.0) 于 2021-08-29 创建的示例
【问题讨论】:
-
致所有人:我想在这里给出第二个答案。因为我刚刚使用cross为我解决了一个大问题。我认为值得分享。这可以吗,还是我应该更新我的第一个答案?我读了这个 meta.stackexchange.com/questions/25209/…> 但我不确定。非常感谢!