【问题标题】:R grepl in dataframe数据框中的R grepl
【发布时间】:2019-08-17 19:32:13
【问题描述】:

我正在尝试检查列中的字符串是否出现在不同的列中。我试过grepl

grepl("b", "d,b,c", fixed = TRUE)
> TRUE

在“独立”对象上运行良好,但在数据框中:

 df = data.frame(id = c("a","b"), ids = c("b,c", "d,b,c")) %>%
     mutate(match = grepl(id, .$ids, fixed = TRUE), truematch = c(FALSE, TRUE))

> df
  id   ids match truematch
1  a   b,c FALSE     FALSE
2  b d,b,c FALSE      TRUE

它没有达到我的预期,即我正在尝试创建列 truematch 但我只能生成 match

【问题讨论】:

    标签: r grepl


    【解决方案1】:

    由于grepl 没有向量化,我们可以使用rowwise 将其应用于每一行

    library(dplyr)
    
    df %>%
      rowwise() %>%
      mutate(truematch = grepl(id, ids, fixed = TRUE))
    
    #  id    ids   match truematch
    #  <fct> <fct> <lgl> <lgl>    
    #1 a     b,c   FALSE FALSE    
    #2 b     d,b,c FALSE TRUE     
    

    但是,rowwise 有点过时了,我们可以将purrr::map2_lglgrepl 一起使用

    df %>% mutate(truematch = purrr::map2_lgl(id, ids, grepl, fixed = TRUE))
    

    但是,对于这种情况,更好的选择是stringr::str_detect,它通过字符串和模式进行矢量化

    df %>% mutate(truematch = stringr::str_detect(ids, fixed(id)))
    

    【讨论】:

      【解决方案2】:

      通过在grepl 上使用sapply

       df %>%  mutate(match = sapply(1:nrow(.),function(x) grepl(.$id[x], .$ids[x])))
      

      给予,

        id   ids  match
      1  a   b,c FALSE
      2  b d,b,c  TRUE
      

      【讨论】:

        猜你喜欢
        • 2019-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多