Markus.london - 6 months ago 51

R Question

I have data that looks like this

`A B`

1 1 1

2 3

3 5

4 7

where I want to calculate the following rolling cumulative product in column B. In Excel I would have the following formula

`B2 = (1 + A2/10)*B1`

I so far have tried using a helper column that is the results of 1 + Ax/100 , and one exactly the same just lagged by 1 which then gets multiplied by each other. Which wont work as the rolling product isn't applied. I also tried s.th like

`rollapply(columnm,1,FUN = prod, fill = NA, align = 'left')`

unfortunately it still doesn't work.

I would expect to get these results for B

`A B`

1 1 1

2 3 1.3

3 5 1.95

4 7 3.315

Answer

Is this what you want?

```
A=c(1,3,5,7)
cumprod(c(1,(A[-1]/10+1)))
> cbind(A,B=cumprod(c(1,(A[-1]/10+1))))
A B
[1,] 1 1.000
[2,] 3 1.300
[3,] 5 1.950
[4,] 7 3.315
```