使用dplyr和stringr检测多个字符串

r.b*_*bot 11 r stringr dplyr

我正在尝试将dplyr和stringr结合起来检测数据帧中的多个模式.我想使用dplyr,因为我想测试许多不同的列.

这是一些示例数据:

test.data <- data.frame(item = c("Apple", "Bear", "Orange", "Pear", "Two Apples"))
fruit <- c("Apple", "Orange", "Pear")
test.data
        item
1      Apple
2       Bear
3     Orange
4       Pear
5 Two Apples
Run Code Online (Sandbox Code Playgroud)

我想用的是:

test.data <- test.data %>% mutate(is.fruit = str_detect(item, fruit))
Run Code Online (Sandbox Code Playgroud)

并收到

        item is.fruit
1      Apple        1
2       Bear        0
3     Orange        1
4       Pear        1
5 Two Apples        1
Run Code Online (Sandbox Code Playgroud)

一个非常简单的测试工作

> str_detect("Apple", fruit)
[1]  TRUE FALSE FALSE
> str_detect("Bear", fruit)
[1] FALSE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)

但即使没有dplyr,我也无法在数据框的列上工作:

> test.data$is.fruit <- str_detect(test.data$item, fruit)
Error in check_pattern(pattern, string) : 
  Lengths of string and pattern not compatible
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?

Rob*_*ski 21

str_detect只接受长度为1的模式.使用paste(..., collapse = '|')或使用any以下内容将其转换为一个正则表达式:

sapply(test.data$item, function(x) any(sapply(fruit, str_detect, string = x)))
# Apple       Bear     Orange       Pear Two Apples
#  TRUE      FALSE       TRUE       TRUE       TRUE

str_detect(test.data$item, paste(fruit, collapse = '|'))
# [1]  TRUE FALSE  TRUE  TRUE  TRUE
Run Code Online (Sandbox Code Playgroud)


Hen*_*rik 13

这种简单的方法适用于EXACT匹配:

test.data %>% mutate(is.fruit = item %in% fruit)
# A tibble: 5 x 2
        item is.fruit
       <chr>    <lgl>
1      Apple     TRUE
2       Bear    FALSE
3     Orange     TRUE
4       Pear     TRUE
5 Two Apples    FALSE
Run Code Online (Sandbox Code Playgroud)

这种方法适用于部分匹配(这是问题):

test.data %>% 
rowwise() %>% 
mutate(is.fruit = sum(str_detect(item, fruit)))

Source: local data frame [5 x 2]
Groups: <by row>

# A tibble: 5 x 2
        item is.fruit
       <chr>    <int>
1      Apple        1
2       Bear        0
3     Orange        1
4       Pear        1
5 Two Apples        1
Run Code Online (Sandbox Code Playgroud)