Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table %like% with logical AND

I am trying to build a Shiny app that is a search engine. I am returning a data.table based on the search keywords:

DT <- data.table(field = c("A_B_C","A_C_D","A_D_A","B_A_D","B_C_F","B_D_K"))

DT[field %like% "A|B"]

The above returns all fields containing A OR B. If I want to have A & B:

DT[field %like% "A"][field %like% "B"]

Is there a syntax that will allow me to do the above for any number of keywords. Something like:

DT[field %like% "A & B & C"]
like image 310
Ivan P. Avatar asked Oct 19 '16 12:10

Ivan P.


2 Answers

If there are only two elements, compare them separately, then do a & and subset the dataset

DT[field %like% "A" & field %like% "B"]
#  field
#1: A_B_C
#2: B_A_D

If there are many strings to compare use Reduce with Map.

DT[Reduce(`&`, Map(`%like%`, list(field), c("A", "B")))]
#    field
#1: A_B_C
#2: B_A_D
like image 151
akrun Avatar answered Oct 15 '22 09:10

akrun


Or you can use Perl-style regex, in combination with grepl inside your data.table:

pat <- "(?=.*A)(?=.*B)"
DT[grep(pat, field, perl = TRUE),]
#   field
#1: A_B_C
#2: B_A_D
like image 43
mtoto Avatar answered Oct 15 '22 11:10

mtoto