简体   繁体   English

R data.table%like%with logical AND

[英]R data.table %like% with logical AND

I am trying to build a Shiny app that is a search engine. 我正在尝试构建一个搜索引擎的Shiny应用程序。 I am returning a data.table based on the search keywords: 我根据搜索关键字返回data.table:

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: 以上内容返回包含A或B的所有字段。如果我想要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 . 如果要比较许多字符串,请使用ReduceMap

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 : 或者你可以使用Perl的正则表达式的风格 ,结合grepl您的内部data.table

pat <- "(?=.*A)(?=.*B)"
DT[grep(pat, field, perl = TRUE),]
#   field
#1: A_B_C
#2: B_A_D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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