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

后端 未结 7 2322
北海茫月
北海茫月 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:24

    To add example to create new columns based on a string vector of columns. Based on Jfly answer:

    dt <- data.table(a = rnorm(1:100), b = rnorm(1:100), c = rnorm(1:100), g = c(rep(1:10, 10)))
    
    col0 <- c("a", "b", "c")
    col1 <- paste0("max.", col0)  
    
    for(i in seq_along(col0)) {
      dt[, (col1[i]) := max(get(col0[i])), g]
    }
    
    dt[,.N, c("g", col1)]
    

提交回复
热议问题