【问题标题】:R - test if a string vector contains any element of another list [duplicate]R - 测试字符串向量是否包含另一个列表的任何元素[重复]
【发布时间】:2018-11-13 07:13:39
【问题描述】:

我有:

> lst_A <- c("TET","RNR")
> DT_result <- data.table(lst_B = c("RNR_B","BC_TET"))

我想要:

> DT_result <- data.table(lst_B = c("RNR_B","BC_TET"), result = c(TRUE,TRUE))
> DT_result
    lst_B result
1:  RNR_B   TRUE
2: BC_TET   TRUE

基本上,对于“lst_B”中的每个元素,如果它包含“lst_A”中的任何元素,则为 TRUE,否则为 FALSE。

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: r string data.table grepl contain


【解决方案1】:

您可以使用grepl 获取此信息。

lst_A <- c("TET","RNR")
lst_B = c("RNR_B","BC_TET")

Pattern = paste(lst_A, collapse="|")
grepl(Pattern, lst_B)

library(data.table)
DT_result <- data.table(lst_B, result=grepl(Pattern, lst_B))
DT_result
    lst_B result
1:  RNR_B   TRUE
2: BC_TET   TRUE

加法

要回复评论,这里有一个示例,其中包含更多要测试的字符串。有些人通过了测试,有些人没有。

lst_A <- c("TET","RNR")
lst_B = c("RNR_B","BC_TET", "Fred", "RNR_A", "Zero", "ABC_TET")

Pattern = paste(lst_A, collapse="|")

DT_result <- data.table(lst_B, result=grepl(Pattern, lst_B))
DT_result
     lst_B result
1:   RNR_B   TRUE
2:  BC_TET   TRUE
3:    Fred  FALSE
4:   RNR_A   TRUE
5:    Zero  FALSE
6: ABC_TET   TRUE

【讨论】:

    【解决方案2】:
        DT_result[,results:=sapply(lst_A,function(x)any(grepl(x,lst_B)))][]
        lst_B results
    1:  RNR_B    TRUE
    2: BC_TET    TRUE
    

    【讨论】:

      【解决方案3】:

      使用grepl 遍历每个选项,然后与|('OR')组合:

      DT_result[, hit := Reduce(`|`, Map(grepl, lst_A, .(lst_B)))]
      DT_result
      
      #    lst_B  hit
      #1:  RNR_B TRUE
      #2: BC_TET TRUE
      

      【讨论】:

        【解决方案4】:

        使用stringrstr_detect

        stringr::str_detect(DT_result$lst_B,'TET|RNR')
        [1] TRUE TRUE
        
        #DF['hit']=stringr::str_detect(DT_result$lst_B,'TET|RNR')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-13
          • 2022-11-14
          • 2019-03-13
          • 2020-04-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多