** первая часть вашего кода **
library(dplyr)
DF1 <- data.frame(det = as.Date(c('2013-02-02','2018-01-11','2011-07-10')),nos = c("1|3","4|2|1","3|4")) %>% print
DF2 <- data.frame(det1 = as.Date(c('2013-02-02','2018-01-11')),no = c(1,3)) %>% print
DF1 = left_join(DF2,DF1,by=c('det1'='det')) # no need to strsplit()
Используйте grepl
с apply
, только одну строку:
DF1$present <- apply(DF1, 1, function(x){
ifelse(grepl(x=x[3], pattern = paste0("(?<!\\d)", x[2], "(?!\\d)"), perl = TRUE), T, F)
})
Результат:
det1 no nos present
1: 2013-02-02 1 1|3 TRUE
2: 2018-01-11 3 4|2|1 FALSE
Это решение "переносимо" на data.table
, например:
library(data.table)
data.table::setDT(DF1) # into data.table
DF1[, present := apply(DF1, 1, function(x){
ifelse(grepl(x=x[3], pattern = paste0("(?<!\\d)", x[2], "(?!\\d)"), perl = TRUE), T, F)
})] # the := is a symbol for assignment