r - 仅保留列表中包含另一个向量 (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 的列表。
谢谢!
解决方案
一种选择是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"
或使用sapply
paragraph[sapply(paragraph, function(x) any(words %in% x))]
或使用lengths
和intersect
paragraph[lengths(Map(intersect, list(words), paragraph)) > 0]
或keep
从purrr
library(purrr)
keep(paragraph, ~ any(words %in% .x))
推荐阅读
- python - 上采样时如何处理熊猫重采样中时间序列的结束?
- c - 为什么 valgrind 报告 glibc tsearch() 随机泄漏内存?
- python - `tuple(None)` 和 `(None,)` 有什么区别?
- python-requests - Python 3.6.5:即使指定了 chunk_length,流请求也会卡在 iter_content 中
- java - 使用 Java 从链式方法中的 Setter 和 Getter 方法中检索特定值
- python-3.x - 如何在画布中获取当前文件的名称
- postgresql - AWS 中的 Oracle FDW 支持
- c# - 在鼠标移动中设置边界
- php - 使用 PHP 在 JSON 文件中搜索带有德语字符的字符串
- java - int low 和 int high 之间的数字之和;爪哇