使用dplyr和stringr检测多个字符串 [英] Detect multiple strings with dplyr and stringr

查看:85
本文介绍了使用dplyr和stringr检测多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to combine dplyr and stringr to detect multiple patterns in a dataframe. I want to use dplyr as I want to test a number of different columns.

以下是一些示例数据:

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

我想使用的是:

test.data <- test.data %>% mutate(is.fruit = str_detect(item, fruit))

并接收

        item is.fruit
1      Apple        1
2       Bear        0
3     Orange        1
4       Pear        1
5 Two Apples        1

一个非常简单的测试工具

A very simple test works

> str_detect("Apple", fruit)
[1]  TRUE FALSE FALSE
> str_detect("Bear", fruit)
[1] FALSE FALSE FALSE

但是我可以即使没有dplyr,也无法在数据框的列上使用它:

But I can't get this to work over the column of the dataframe, even without dplyr:

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

有人知道怎么做吗?

推荐答案

str_detect 仅接受长度为1的模式。使用 paste(...,crash ='|')将其转换为一个正则表达式,或者使用 any

str_detect only accepts a length-1 pattern. Either turn it into one regex using paste(..., collapse = '|') or use 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

这篇关于使用dplyr和stringr检测多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆