我有一个包含一列字符串的数据框,我想使用 filter() (或另一个可管道函数)仅返回包含字符串的行,这些字符串包含另一个字符串向量中的任何值。我已经查看了以前的问题和答案,但找不到任何我正在寻找的东西。
例如:
title <- c("apple pie", "fish pie", "peach strudel", "banana split", "chocolate cake", "pasta", "peaches and cream", "baked apples")
recipes <- data.frame(cbind(c(1:8), title))
fruits <- c("apple", "banana", "peach", "orange")
如何过滤食谱以仅返回recipes$title 包含水果中任何内容的行?
我们可以用str_detect
with filter
从“fruits”创建单个字符串后collapse
d by |
(OR)
library(dplyr)
library(stringr)
recipes %>%
filter(str_detect(title, str_c(fruits, collapse="|")))
# V1 title
#1 1 apple pie
#2 3 peach strudel
#3 4 banana split
#4 7 peaches and cream
#5 8 baked apples
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)