Orhan Yazar
Orhan Yazar

Reputation: 909

Is it possible to aggregate data.table using column number and not column names in large dataset?

I'm trying to aggregate a data.table. To be more precise, i have a data.table with 202 column, i want to aggregate(dt[,131:202]~dt[,1:130],data=dt,FUN=sum). Here is a data.table so you can try to do 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)

Upvotes: 3

Views: 603

Answers (1)

akrun
akrun

Reputation: 887671

The data.table option would be to specify the columns of interest in .SDcols, grouping columns in by, loop over the .SD (Subset of data.table) and get the sum

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))

Upvotes: 4

Related Questions