如何使用dplyr :: filter()仅返回值包含一个或多个给定字符串向量的行? [英] How to use dplyr::filter() to return only rows where the value contains one or more of a given vector of strings?
本文介绍了如何使用dplyr :: filter()仅返回值包含一个或多个给定字符串向量的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含一列字符串的数据框,并且我想使用filter()(或另一个可传递函数)仅返回包含字符串的行,这些行包含另一个字符串向量中的任何值。我已经看过以前的问题和答案,但是找不到我所要查找的任何东西。
I have a dataframe containing a column of strings, and I want to use filter() (or another pipeable function) to return only rows containing strings that contain any of the values in another vector of strings. I have looked at previous questions and answers but can't find anything that's quite what I'm looking for.
例如:
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")
如何过滤配方以
推荐答案
我们只能使用 str_detect
使用过滤器
从'fruits' collapse
d创建一个字符串后, |
(OR)
We can use str_detect
with filter
after creating a single string from '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
这篇关于如何使用dplyr :: filter()仅返回值包含一个或多个给定字符串向量的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文