grep one pattern over multiple columns

空扰寡人 提交于 2019-12-08 16:30:30

I'd probably do this:

temp = sapply(your_data[columns_you_want_to_check],
              function(x) grepl("suspected", x, ingore.case = TRUE))
your_data$abnormal = rowSums(temp) > 0

I just used your_data since your question switches between df and test.file.

If you really want to use mutate, you could do

df %>%
mutate(abnormal = rowSums(
  sapply(select(., starts_with("var")),
         function(x) grepl("suspected", x, ingore.case = TRUE)
  )) > 0
)

If you need more efficiency, you can use fixed = TRUE instead of ignore.case = TRUE if you can count on the case being consistent. (Maybe convert everything to_lower() first.)

Leave off the > 0 to get the count for each row.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!