Is it possible to aggregate data.table using column number rather than columns in a large dataset?

I am trying to concatenate a data.table. To be more precise, I have a data.table with a 202 column I want aggregate(dt[,131:202]~dt[,1:130],data=dt,FUN=sum)

. Here is the datasheet, so you can try it.

A <- c(1,2,3,4,4,6,4)
B <- c("a","b","c","d","e","f","g")
C <- c(10,11,23,8,8,1,3)
D <- c(2,3,5,9,7,8,4)
E <- c(2,5,7,1,4,6,15)
G <- c("b","f","s","k","t","r","n")
H <- c(2,68,5,27,11,17,4)


dt <- data.table(A,B,C,D,E,G,H)

      

+3


source to share


1 answer


The data.table parameter will point the columns of interest in .SDcols

, grouping the columns in by

, .SD

iterate through (.table data subset) and getsum

dt[, lapply(.SD, sum), by = c(names(dt)[1:130]), .SDcols = 131:202]

      



data

set.seed(24)
d1 <- as.data.frame(matrix(sample(LETTERS[1:7], 130*20, replace = TRUE),
        20, 130), stringsAsFactors=FALSE)
d2 <- as.data.frame(matrix(sample(1:20, 130*20, replace = TRUE), 20, 
       130), stringsAsFactors=FALSE)
dt <- data.table(d1, d2)
names(dt) <- make.unique(names(dt))

      

+4


source







All Articles