Take a look at my answer to this question: Mean per group in a data.frame
Your question is similar. If you change the function being applied from mean to sum, you get what you are looking for.
colstosum <- names(mydt)[2:5]
mydt.sum <- mydt[,lapply(.SD,sum,na.rm=TRUE),by=colID,.SDcols=colstosum]
mydt.sum
colID colSparse1 cPlSpars2 coMSparse3 colSpArseN
1: 1 2 2 2 2
2: 2 2 2 2 2
3: 3 1 1 1 0
4: 4 2 1 2 1
5: 5 2 1 2 1
6: 6 0 0 1 0
Granted, I can't guarantee the speed or lack thereof of sum
on a large data.table
. Also, there is a way you should be able to incorporate colSums
in the lapply function, but I can't figure out the syntax at the moment.