首页 > 解决方案 > 仅保留列表中包含另一个向量 (R) 中的字符串的元素

问题描述

我有一个字符串关键字向量和一个包含许多字符串元素的列表。我想保留列表中至少包含一个来自向量的字符串的元素。

我尝试过使用 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"))

我想最终得到一个仅包含 text1 和 text3 的列表。

谢谢!

标签: rregexstringlistfind

解决方案


一种选择是Filterbase 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"

或使用sapply

paragraph[sapply(paragraph, function(x) any(words %in% x))]

或使用lengthsintersect

paragraph[lengths(Map(intersect, list(words), paragraph)) > 0]

keeppurrr

library(purrr)
keep(paragraph, ~ any(words %in% .x))

推荐阅读