Mar*_* W. 1 regex string r list find
我有一个字符串关键字向量,以及一个包含许多带有字符串的元素的列表。我想保留至少包含向量中一个字符串的列表元素。
我试过用 dplyr、%in% 等过滤。
下面是一个例子:
words <- c("find", "these", "words")
paragraph <- list(text1 = c("these", "words", "are", "helpful"),
text2 = c("nothing", "to", "see", "here"),
text3 = c("we", "can", "find", "one", "here"))
Run Code Online (Sandbox Code Playgroud)
我想最终得到一个只包含 text1 和 text3 的列表。
谢谢!
一种选择是Filter从base R. 创建一个vector带有%in%包装的逻辑any
Filter(function(x) any(words %in% x), paragraph)
#$text1
#[1] "these" "words" "are" "helpful"
#$text3
#[1] "we" "can" "find" "one" "here"
Run Code Online (Sandbox Code Playgroud)
或使用 sapply
paragraph[sapply(paragraph, function(x) any(words %in% x))]
Run Code Online (Sandbox Code Playgroud)
或者使用lengths和intersect
paragraph[lengths(Map(intersect, list(words), paragraph)) > 0]
Run Code Online (Sandbox Code Playgroud)
或keep从purrr
library(purrr)
keep(paragraph, ~ any(words %in% .x))
Run Code Online (Sandbox Code Playgroud)