将过滤条件应用于 contain/start 具有 R 中特定字符串的变量

Apply filter criteria to variables that contain/start with certain string in R

我正在尝试找到一种方法来根据应用于名称包含特定字符串的变量的标准来过滤数据框

在下面的这个例子中, 我想找到他们的任何测试结果包含“d”的主题。

d=structure(list(ID = c("a", "b", "c", "d", "e"), test1 = c("a", "b", "a", "d", "a"), test2 = c("a", "b", "b", "a", "s"), test3 = c("b", "c", "c", "c", "d"), test4 = c("c", "d", "a", "a", "f")), class = "data.frame", row.names = c(NA, -5L))

我可以使用 dplyr 并使用 | 一个一个地写,这适用于像这样的小例子,但对于我的真实数据将是耗时的。

library(dplyr) library(stringr) d %>% filter(str_detect(d$test1, "d") |str_detect(d$test2, "d") |str_detect(d$test3, "d") |str_detect(d$test4, "d") )

我得到的输出显示受试者 b、d 和 e 符合条件:

ID test1 test2 test3 test4 1 b b b c d 2 d a c a 3 e a s d f

输出是我需要的,但我一直在寻找一种更简单的方法,例如,如果有一种方法可以将过滤条件应用于包含单词“test”的变量 我知道 dplyr 中的 contain 函数到 select 某些变量,我在这里尝试过但没有用,

d %>% filter(str_detect(contains("test"), "d"))

有没有办法以不同的方式编写此代码,或者是否有其他方法可以实现相同的目标?

谢谢

在基础 R 中你可以使用 lapply/sapply :

d[Reduce(`|`, lapply(d[-1], grepl, pattern = 'd')), ]
#d[rowSums(sapply(d[-1], grepl, pattern = 'd')) > 0, ]


#  ID test1 test2 test3 test4
#2  b     b     b     c     d
#4  d     d     a     c     a
#5  e     a     s     d     f

如果您对 dplyr 解决方案感兴趣,您可以使用以下任何一种方法:

library(dplyr)
library(stringr)

#1.
d %>% 
  filter_at(vars(starts_with('test')), any_vars(str_detect(., 'd')))

#2.
d %>%
  rowwise() %>%
  filter(any(str_detect(c_across(starts_with('test')), 'd')))

#3.
d %>%
  filter(Reduce(`|`, across(starts_with('test'), str_detect, 'd')))