如何在给定的单词列表中查找包含单词的行?不仅是某个词,那个特定列表中的任何词都很重要

How to find rows which contain words in a given list of words? Not only a certain word, any word in that certain list counts

我有一个给定的单词列表,例如:

words <- c("breast","cancer","chemotherapy")

我有一个非常大的数据框,1 个变量和超过 10,000 个条目(行)。

我想 select 包含 "words" 中任何单词的所有行。不仅是某个词,"words"中的任何一个词都算。包含 "words" 中的多个单词也算在内。

如果我知道 "words" 是什么,我可以多次提取 stringr。但是,"words"每次都变了,看不到。有什么直接的方法吗?

此外,我是否有可能 select "words" 中包含 2 个或更多单词的所有行?例如。仅包含 "cancer" 不算数,但包含 "breast" 和 "cancer" 算在内。同样,"words" 每次都会更改,并且无法看到。有直接的方法吗?

一些假数据:

words <- c("breast","cancer","chemotherapy")
df <- data.frame(v1 = c("there was nothing found","the chemotherapy is effective","no cancer no chemotherapy","the breast looked normal","something"))

您可以组合使用 greplsapplyrowSums:

df[rowSums(sapply(words, grepl, df$v1)) > 0, , drop = FALSE]

这导致:

                             v1
2 the chemotherapy is effective
3     no cancer no chemotherapy
4      the breast looked normal

如果只想选择至少有两个单词的行,那么:

df[rowSums(sapply(words, grepl, df$v1)) > 1, , drop = FALSE]

结果:

                             v1
3     no cancer no chemotherapy

注意:您需要使用 drop = FALSE 因为您的数据框只有一个变量(列)。如果您的数据框有多个变量(列),则不需要使用 drop = FALSE