【问题标题】:detect string with both AND and OR boolean operator in R在 R 中使用 AND 和 OR 布尔运算符检测字符串
【发布时间】:2019-09-17 18:43:19
【问题描述】:

我有这样的文字:

text = 'I love apple, pear, grape and peach'

如果我想知道文本是否包含applepear。我可以执行以下操作并且工作正常:

str_detect(text,"apple|pear")
[1] TRUE

我的问题是,如果我想使用像 (apple OR pear) AND (grape) 这样的布尔值怎么办。 无论如何我可以把它放在str_detect()。那可能吗? 以下是工作:

str_detect(text,"(apple|pear) & (grape)" )
[1] FALSE

我想知道这一点的原因是我想编程转换一个“布尔查询”并输入grepstr_detect。类似:

str_detect(text, '(word1|word2) AND (word2|word3|word4) AND (word5|word6) AND .....')

AND 的数量不等......

请解决多个str_detect 的问题。

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    您可以将所有模式作为向量传递给 str_detect,并检查它们是否都是 TRUEall

    patterns <- c('apple|pear', 'grape')
    all(str_detect(text, patterns))
    

    或以 R 为基数

    all(sapply(patterns, grepl, x = text))
    

    或者,您可以将模式放在列表中并使用映射,这将为 OR(或您可能希望作为列表元素放置的任何其他内容)提供更详细的输出

    patterns <- list(c('apple', 'pear'), 'peach')
    patterns %>% 
      map(str_detect, string = text)
    
    # [[1]]
    # [1] TRUE TRUE
    # 
    # [[2]]
    # [1] TRUE
    

    也可以将其写为单个正则表达式,但我认为没有理由这样做

    patterns <- c('apple|pear', 'grape')
    patt_combined <- paste(paste0('(?=.*', patterns, ')'), collapse = '')
    str_detect(text, patt_combined)
    

    patt_combined

    # [1] "(?=.*apple|pear)(?=.*grape)"
    

    【讨论】:

    • 基于map 的方法非常好的一点是,在调用reduce 之前,您可以准确地看到哪些字符串与哪些模式匹配。当有更多字符串要测试时,这很有用
    • 我实际上在您从 map 更改为 map_lgl 之前写了 ^^ 那条评论。 map + reduce 可让您测试字符串向量,而当前的 map_lgl + all 版本没有
    • 不确定你的意思,在这种情况下,我认为map_lgl 的输出与map 的输出没有任何信息丢失,对吧?两者都没有命名,它只是一个逻辑值列表与一个逻辑向量,你仍然可以看到哪些模式匹配。
    • 我制作了一个包含 3 个字符串的向量来进行测试。如果我打电话给map_lgl(patt, ~str_detect(text, .)),我会收到一个错误,因为map_lgl 需要返回一个值,而是试图返回3。这可以通过将all inside map_lgl 来解决称呼。我认为这两种方式都很好(并且都值得保留在 IMO 的答案中)
    • 我明白了,我什至没有意识到 str_detect 函数在 pattern 参数中被矢量化,我认为它就像 grepl。重新输入map 选项,谢谢
    猜你喜欢
    • 2016-07-03
    • 2013-10-13
    • 1970-01-01
    • 2021-11-06
    • 2013-02-09
    • 2014-05-30
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多