0

In this MVCE snippet, why is it not possible to use .SD[1:round] in this way?

And is there a way to twist data.table into submission?

> test <- data.table(event = c(1,1,1,2,2), round = c(seq(1,3),seq(1,2)), cost = seq(20,60,10))
> test
   event round cost
1:     1     1   20
2:     1     2   30
3:     1     3   40
4:     2     4   50
5:     2     5   60

> test[,.(cumulative=sum(.SD[1:round]$cost)),by=.(event)]
   event cumulative
1:     1         20
2:     2         NA
Warning messages:
1: In 1:round : numerical expression has 3 elements: only the first used
2: In 1:round : numerical expression has 2 elements: only the first used

Desired Result:

   event round cumulative
1:     1     1         20
2:     1     2         50
3:     1     3         90
4:     2     1         50
5:     2     2        110
Zaid
  • 36,680
  • 16
  • 86
  • 155

0 Answers0