4

From a data.table d such as for example

require(data.table)
d = data.table(a = 1:4, b = 11:14, c = 21:24, group = c(1,1,2,2))

I would like to sum all variables which names are stored in the vector varsToSum by unique values of group.

varsToSum = c("a", "b")

For the above d and varsToSum, the expected outcome is

d[,list(a = sum(a), b = sum(b)),list(group)]

   group a  b
    1: 1 3 23
    2: 2 7 27

Related posts:

Michael Ohlrogge
  • 10,559
  • 5
  • 48
  • 76
Remi.b
  • 17,389
  • 28
  • 87
  • 168

1 Answers1

8
d[, lapply(.SD, sum), by = group, .SDcols = varsToSum]

   group a  b
1:     1 3 23
2:     2 7 27
Michael Ohlrogge
  • 10,559
  • 5
  • 48
  • 76