Elegantly assigning multiple columns in data.table with lapply()

后端 未结 3 960
迷失自我
迷失自我 2020-11-28 21:14

I am trying to figure out an elegant way to use := assignment to replace many columns at once in a data.table by applying a shared function. A typi

3条回答
  •  时光说笑
    2020-11-28 21:56

    These should work if you want to refer to the columns by string name:

    n = paste0("V", 20:100)
    dt[, (n) := lapply(n, function(x) {sqrt(get(x))})]
    

    or

    dt[, (n) := lapply(n, function(x) {sqrt(dt[[x]])})]
    

提交回复
热议问题