Gen*_*Rus 4 r stringr dplyr purrr tibble
我正在尝试清理来自许多不同组的样本信息表,因此我关心的治疗信息可能位于任意数量的不同列中。这是一个抽象的例子:
sample_info = tribble(
~id, ~could_be_here, ~or_here, ~or_even_in_this_one,
1, NA, "not_me", "find_me_other_stuff",
2, "Extra_Find_Me", NA, "diff_stuff",
3, NA, "Find_me", NA,
4, NA, "not_here", "not_here_either"
)
Run Code Online (Sandbox Code Playgroud)
我想在哪里找到“find_me”1)不区分大小写,2)它可以在任何列中,3)它可以作为更大字符串的一部分。我想创建一列,判断是否在任何列中找到“find_me”,该列为 TRUE 或 FALSE。我怎样才能做到这一点?(我想过对unite所有列进行 ing,然后str_detect在混乱的情况下运行 a,但一定有一种不那么老套的方法,对吧?)
需要明确的是,我想要一个相当于 的最终小标题sample_info %>% mutate(find_me = c(TRUE, TRUE, TRUE, FALSE))。
我希望在下面链接的类似情况下使用类似的东西stringr::str_detect(., regex('find_me', ignore_case = T)),pmap_lgl(any(c(...) <insert logic check>))但我不确定如何将它们组合成一个兼容变异的语句。
我查看过的内容:
按行操作查看是否有任何列位于任何其他列表中
一种dplyr选择purrr可能是:
sample_info %>%
mutate(find_me = pmap_lgl(across(-id), ~ any(str_detect(c(...), regex("find_me", ignore_case = TRUE)), na.rm = TRUE)))
id could_be_here or_here or_even_in_this_one find_me
<dbl> <chr> <chr> <chr> <lgl>
1 1 <NA> not_me find_me_other_stuff TRUE
2 2 Extra_Find_Me <NA> diff_stuff TRUE
3 3 <NA> Find_me <NA> TRUE
4 4 <NA> not_here not_here_either FALSE
Run Code Online (Sandbox Code Playgroud)
或者只使用dplyr:
sample_info %>%
rowwise() %>%
mutate(find_me = any(str_detect(c_across(-id), regex("find_me", ignore_case = TRUE)), na.rm = TRUE))
Run Code Online (Sandbox Code Playgroud)