DT <- data.table(num=c(\"20031111\",\"1112003\",\"23423\",\"2222004\"),y=c(\"2003\",\"2003\",\"2003\",\"2004\")) > DT num y 1: 20031111 2003 2: 111200
You could do this
DT[, x := grep(y, num, value = TRUE, fixed = TRUE), by = .(num, y)] #> DT # num y x #1: 20031111 2003 20031111 #2: 1112003 2003 1112003 #3: 23423 2003 NA #4: 2222004 2004 2222004