正则表达式 – 通过data.table(R)循环grepl()

我有一个数据集存储为data.table DT,如下所示:
print(DT)
   category            industry
1: administration      admin
2: nurse practitioner  truck
3: trucking            truck
4: administration      admin
5: warehousing         nurse
6: warehousing         admin
7: trucking            truck
8: nurse practitioner  nurse         
9: nurse practitioner  truck

我想将表减少到只有行业匹配类别的行.我的一般方法是使用grepl()来匹配字符串’^ {{INDUSTRY}} [az] $’和DT $category的每一行,并插入每个对应的DT $行代替{{INDUSTRY}使用infuse()在正则表达式字符串中.我很难找到一个时髦的data.table解决方案,它可以正确地循环遍历表并进行行内比较,所以我使用for循环来完成工作:

template <- "^{{IND}}[a-z ]+$"
DT[,match := FALSE,]
for (i in seq(1,length(DT$category))) {
    ind <- DT[i]$industry
    categ <- d.daily[i]$category
    if (grepl(infuse(IND=ind,template),categ)){
        DT[i]$match <- TRUE
    }
}
DT<- DT[match==TRUE]
print(DT)
       category            industry
1: administration      admin
2: trucking            truck
3: administration      admin
4: trucking            truck
5: nurse practitioner  nurse

但是,我确信这可以通过更好的方式完成.有关如何通过利用data.table包的功能实现此结果的任何建议?我的理解是,在这种情况下,使用包的方法可能比for循环更有效.

Data.table擅长分组操作;我认为这是有用的,假设你有很多行具有相同的行业:
DT[ DT[,.I[grep(industry,category)],by = industry]$V1 ]

这使用the current idiom for subsetting by group,thanks to @eddi .

注释.这可能有助于进一步:

>如果您有许多行具有相同的行业类别组合,请尝试=.(行业,类别).>在grep的地方尝试别的东西(比如Ken和Richard的答案中的选项).

相关文章

jquery.validate使用攻略(表单校验) 目录 jquery.validate...
/\s+/g和/\s/g的区别 正则表达式/\s+/g...
自整理几个jquery.Validate验证正则: 1. 只能输入数字和字母...
this.optional(element)的用法 this.optional(element)是jqu...
jQuery.validate 表单动态验证 实际上jQuery.validate提供了...
自定义验证之这能输入数字(包括小数 负数 ) &lt;script ...