I need to create a column in which each observation equals the value of the previous observation multiplied by an observation in another column plus 1. I'm trying to create the indx column in the example below. indx[1] is hard coded as 1.000, but indx[2] = indx[1]*(1+chng[2]).
I've been using mutate in the dplyr library to make new columns, but I don't see how I can reference the previous value of a column as I'm creating it.
Edit: Updated the below example to include to reflect that the data values for i and chng reset to 0 and 0.000 respectively after every 5 observations and that indx would need to reset to 1.000 when this happens as well and begin it's accumulation again.
Example data.table:
test <- data.frame(i = c(0,1,2,3,4,0,1,2,3,4)
,chng = c(.000,.031,.005,-.005,.017,.000,.012,.003,-.013,-.005,)
,indx = c(1,1.031,1.037,1.031,1.048,1,1.012,1.015,1.002,.997))
i chng indx
1: 0 0.000 1.000
2: 1 0.031 1.031
3: 2 0.005 1.037
4: 3 -0.005 1.031
5: 4 0.017 1.048
6: 0 0.000 1.000
7: 1 0.012 1.012
8: 2 0.003 1.015
9: 3 -0.013 1.002
10: 4 -0.005 0.997