【问题标题】:str_detect for multiple patternsstr_detect 用于多种模式
【发布时间】:2019-11-16 10:17:37
【问题描述】:

我在 stringr 包中使用 str_detect,但在搜索超过一种模式。

这是我正在使用的代码,但是即使我的向量(“Notes-Title”)包含这些模式,它也没有返回任何内容。

filter(str_detect(`Notes-Title`, c("quantity","single")))

我要编码的逻辑是:

搜索每一行,如果它包含字符串“数量”或“单个”,则对其进行过滤。

【问题讨论】:

    标签: stringr


    【解决方案1】:

    您需要使用 |搜索中的分隔符,都在一组“”中。

    > words <- c("quantity", "single", "double", "triple", "awful")
    > set.seed(1234)
    > df = tibble(col = sample(words,10, replace = TRUE))
    > df
    # A tibble: 10 x 1
       col     
       <chr>   
     1 triple  
     2 single  
     3 awful   
     4 triple  
     5 quantity
     6 awful   
     7 triple  
     8 single  
     9 single  
    10 triple 
    
    > df %>% filter(str_detect(col, "quantity|single"))
    # A tibble: 4 x 1
      col     
      <chr>   
    1 single  
    2 quantity
    3 single  
    4 single  
    

    【讨论】:

    • 泰勒 - 谢谢,但这对我不起作用。它似乎只适用于单个字符搜索。如果我写“q|s”,它会匹配,但会匹配其中包含 q 或 s 的所有内容。如果它写成 "quantity|single" 它什么都不匹配。
    • @SteveM 抱歉,我在玩具示例中并不清楚。我已经更改了数据集,以便您可以看到 |操作员使用str_detect
    • 这行得通。谢谢。还有一个问题……我如何使它不区分大小写?我尝试使用 fixed("quantity|multiple", ignore_case = TRUE) 但这似乎不起作用
    • 不幸的是,我不知道是否有简单的方法可以做到这一点。您可以添加额外的查询,例如“(quantity|Quantity|single|Single)”,或者您可以更改过滤器 mutate(col = tolower(col)) 前面的列以删除大写
    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2020-03-22
    • 1970-01-01
    相关资源
    最近更新 更多