Using gsub adding new column in a data.table

前端 未结 2 1715
说谎
说谎 2021-01-19 02:28

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

相关标签:
2条回答
  • 2021-01-19 03:03

    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
    
    0 讨论(0)
  • 2021-01-19 03:27
    dt[, v3 := gsub("x", v1, v2), by = v1]  
    
    0 讨论(0)
提交回复
热议问题