Use the “data.table” package! The syntax is much easier, and the run time is faster.
### Load package
require(data.table)
### Set up variables; Create data.table
time <- c(0:4, 7)
ColA <- c(1, 3, 0, 3, 4, 10)
ColB <- c(10, 7, 8, 4, 5, 23)
ColC <- c(5, 15, 9, 5, 6, 4)
data <- data.table(time, ColA, ColB, ColC)
### Determine which columns we want to apply the function to
sum.cols <- grep("Col", names(data), value = T)
### Sum each column within each group
data[, lapply(.SD, sum), by = floor(time / 2), .SDcols = sum.cols]
### Output:
floor ColA ColB ColC
1: 0 4 17 20
2: 1 3 12 14
3: 2 4 5 6
4: 3 10 23 4
Note that the symbol “.SD”, refers to a “Subset of Data”. In this case, the lapply function iterates over columns of the data table, applying the function “sum” to each column. Within each column, sums are calculated for each level of our “floor” variable.
3
solved Sum multiple columns by group [duplicate]