Using gsub adding a new column to data.table

Sorry for the very simple question, the solution should be very simple, but I can not find it.

Trying to use gsub by adding a new column to the data table. I got a warning "The argument" replacement "has a length> 1 and only the first element will be used," and all .table data rows have the value of the first row in a new column.

Here is an example of addition:

dt <- data.table(v1=c(1,2,3) , v2=c("axb","cxxd","exfxgx"))  
dt[ , v3:=gsub("x",v1,v2)]  

The new v3 column contains a row with "1" instead of "x" in all rows.

Using other functions, for example.

dt[ , v3:=paste(v1,v2)]  

works as expected.

I am using Rstudio v.0.98.1103, R v.3.1.2, data.table v.1.9.4

+4
source share
2 answers
dt[, v3 := gsub("x", v1, v2), by = v1]  
+11
source

- , 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

"" gsub Vectorize:

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
+5

All Articles