4

I have:

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

I want:

> 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

Basically, for each element in 'lst_B' if it contains any element in 'lst_A' then TRUE otherwise FALSE.

LeGeniusII
  • 900
  • 1
  • 10
  • 28

4 Answers4

9

You can get this using 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

Addition

To respond to a comment, here is an example with more strings to test. Some pass the test, others not.

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
G5W
  • 36,531
  • 10
  • 47
  • 80
5

Using stringr's str_detect

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

#DF['hit']=stringr::str_detect(DT_result$lst_B,'TET|RNR')
BENY
  • 317,841
  • 20
  • 164
  • 234
4
    DT_result[,results:=sapply(lst_A,function(x)any(grepl(x,lst_B)))][]
    lst_B results
1:  RNR_B    TRUE
2: BC_TET    TRUE
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

Loop over each option with grepl and then combine with an | ('OR'):

DT_result[, hit := Reduce(`|`, Map(grepl, lst_A, .(lst_B)))]
DT_result

#    lst_B  hit
#1:  RNR_B TRUE
#2: BC_TET TRUE
thelatemail
  • 91,185
  • 12
  • 128
  • 188