Home > Mobile >  Reducing rolling product data.table
Reducing rolling product data.table

Time:10-11

I would like to get a reducing rolling product within my group(s) using data.table. That is, the first row in the data set tst below would be the product of all 4 value-observations within group A and orderVal(1:4). The second would be orderVal 2:4, the third 3:4 and the last just 4:4 and so on for all k-groups. I could do it with a for-loop but I know this probably could be done a lot cleaner and more efficently using just data.table.

Reproducible code below:

require(data.table)

tst <- data.table(grp = c(rep("A", 4), rep("B",4)),
                  orderVal = c(rep(seq(1,4),2)),
                  val = c(rep(1.4, 4), rep(1.5, 4)))

CodePudding user response:

You could use Reduce, with accumulate=TRUE option:

tst[order(grp,-orderVal),prod:=Reduce(`*`,val,accumulate=T),by=grp][]

   grp orderVal val   prod
1:   A        1 1.4 3.8416
2:   A        2 1.4 2.7440
3:   A        3 1.4 1.9600
4:   A        4 1.4 1.4000
5:   B        1 1.5 5.0625
6:   B        2 1.5 3.3750
7:   B        3 1.5 2.2500
8:   B        4 1.5 1.5000
  • Related