Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用dplyr::filter()仅返回值包含一个或多个给定字符串向量的行?_R_String_Dplyr - Fatal编程技术网

如何使用dplyr::filter()仅返回值包含一个或多个给定字符串向量的行?

如何使用dplyr::filter()仅返回值包含一个或多个给定字符串向量的行?,r,string,dplyr,R,String,Dplyr,我有一个包含一列字符串的数据帧,我想使用filter或其他可管道函数只返回包含字符串的行,这些字符串包含另一个字符串向量中的任何值。我已经看了以前的问题和答案,但找不到与我所寻找的完全相同的东西 例如: title <- c("apple pie", "fish pie", "peach strudel", "banana split", "chocolate cake", "pasta", "peaches and cream", "baked apples") recip

我有一个包含一列字符串的数据帧,我想使用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")
如何筛选配方以仅返回配方$title包含来自水果的任何内容的行?

我们可以使用str_detect with filter从折叠为|或|的“水果”创建单个字符串


这给了我一个错误:求值错误:参数str应该是一个字符向量或一个可强制的对象。即使我将列从因子显式转换为字符向量(例如,水果配方%mutate\u ifis.factor、~as.character.%%>),也会发生这种情况filterstr_detecttitle,str_cfruits,collapse=|知道我如何解决这个问题吗?@Mel我只使用了你的例子,它对我来说很好,因子列为well@Mel尝试配方%>%filterstr_detectas.charactertitle、str_cas.characterfruits、折叠=|
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