我目前正在使用具有多个相似列的数据集:item1,item2等,直到item8。在我正在编写的函数中,我创建了一个特定的搜索,用作ifelse函数中的第一个参数,用于在以下任何列中搜索短语:
grepl(exact_name, item1) | grepl(exact_name, item2) | grepl(exact_name, item3) | grepl(exact_name, item4) | grepl(exact_name, item5) | grepl(exact_name, item6) | grepl(exact_name, item7) | grepl(exact_name, item8)
这工作正常,但我希望能够将此函数应用于具有一些未知数量的项目列的数据帧(所有使用的数据帧将至少有一个项目列,如果它只有一个,它仍将处于格式item1而不仅仅是item)。我尝试使用*通配符如下:
grepl(exact_name, item*)
但是我在项目*后面有一个括号时出错,甚至无法运行该部分。有一个更好的方法吗?
如果item\\d+
是全局环境中的对象,我们可以使用mget
来获取list
中的对象,然后循环通过list
,将grepl
和Reduce
应用于单个逻辑vector
Reduce(`|`,lapply(mget(ls(pattern = "^item\\d+$")), grepl, pattern = exact_name))
如果item\\d+
是数据集中的列,请使用filter_at
library(dplyr)
df1 %>%
filter_at(vars(matches("^item\\d+$")), any_vars(str_detect(., exact_name)))
另外,如果我们没有进行部分匹配,那么==
应该也可以
df1 %>%
filter_at(vars(matches("^item\\d+$")), any_vars(.== exact_name))