Search code examples
rdata.tablesql-like

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"]

Solution

  • 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