Using initial values, I want to fill iteratively NAs in a data.table column based on growth rates stored in a separate column, by id.
Take the following data.table as an example:
library(data.table)
DT <- data.table(id = c("A","A","A","A","B","B","B","B"), date=1:4,
growth=1L+runif(8), index= c(NA,250,NA,NA,NA,300,NA,NA))
> DT
id date growth index
1: A 1 1.654628 NA
2: A 2 1.770219 250
3: A 3 1.255893 NA
4: A 4 1.185985 NA
5: B 1 1.826187 NA
6: B 2 1.055251 300
7: B 3 1.180389 NA
8: B 4 1.204108 NA
Basically, what I need id for index values after date 2:
index_{i,t} = growth_{i,t}*index_{i,t-1}
And, for values before date 2:
index_{i,t} = index_{i,t-1}/growth_{i,t-1}
I had a go using shift, but this replace just index at t+1:
DT[, index := growth * shift(index,1L, type="lag")]
UPDATE The desired result looks like that
> DT
id date growth index
1: A 1 1.440548 141.2255
2: A 2 1.395092 250.0000
3: A 3 1.793094 313.9733
4: A 4 1.784224 372.3676
5: B 1 1.129264 284.2926
6: B 2 1.978359 300.0000
7: B 3 1.228979 354.1167
8: B 4 1.453433 426.3948
DT[date > 2, index2 := growth * shift(index,1L, type="lag"), by = id]andDT[date < 2, index2 := shift(index,1L) / shift(growth, 1L), by = id]. That makes all NA for your example data. Is your goal to fill all the NAs? - Chris Holbrook