How to apply same function to every specified column in a data.table

后端 未结 7 2319
北海茫月
北海茫月 2020-11-22 08:00

I have a data.table with which I\'d like to perform the same operation on certain columns. The names of these columns are given in a character vector. In this particular ex

7条回答
  •  [愿得一人]
    2020-11-22 08:40

    I would like to add an answer, when you would like to change the name of the columns as well. This comes in quite handy if you want to calculate the logarithm of multiple columns, which is often the case in empirical work.

    cols <- c("a", "b")
    out_cols = paste("log", cols, sep = ".")
    dt[, c(out_cols) := lapply(.SD, function(x){log(x = x, base = exp(1))}), .SDcols = cols]
    

提交回复
热议问题