Sorry for a very basic question, solution must be very simple but I\'m not able to find it.
Trying to use gsub adding a new column in a data.table, I got the warning
The easiest approach would be to use a string processing package that has vectorized arguments, like stringi
:
library(stringi)
dt[, v3 := stri_replace_all_fixed(v2, "x", v1)][]
# v1 v2 v3
# 1: 1 axb a1b
# 2: 2 cxxd c22d
# 3: 3 exfxgx e3f3g3
Alternatively, you can make your own "vectorized" version of gsub
by using the Vectorize
function:
vGsub <- Vectorize(gsub, vectorize.args = c("replacement", "x"))
dt[, v3 := vGsub("x", v1, v2)][]
# v1 v2 v3
# 1: 1 axb a1b
# 2: 2 cxxd c22d
# 3: 3 exfxgx e3f3g3
dt[, v3 := gsub("x", v1, v2), by = v1]