简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM