I'm trying to speed-up this calculation and at least get rid of the inner loop, because it's really slow over a lot of ids. For each ID, I have a vector of "x" values and am trying to calculate "y" values that are dependent on the current value of "x" and the previous value of "y". In other words, for each ID y[1] = x[1] and for subsequent rows, y[i]=y[i-1]*x[i].
Can anyone help me speed this up? I have tried to find solutions but can't figure it out.
Here is some reproducible code that does what I want, but slowly:
#Calculate y[i]=y[i-1]*x[i]
#Make some dummy data
dat<-data.frame(id=c(rep(1,10), rep(2,10)),
x=c(0.95,1,1,1,0.98,0.96,0.93,1,0.94,0.9,
0.97,1,1,0.94,0.93,1,1,0.97,0.99,0.95),
y=rep(0,20))
#Calculate y[i]=x[i]*y[i-1]
idx<-1
#Loop over individuals
ids<-unique(dat$id)
for (j in 1:length(ids)){
#Extract data for individual i
temp<-dat[dat$id==ids[j],]
#Initialize y[1]=x[1]
temp$y[1]<-temp$x[1]
#Calculate y[i]=x[i]*y[i-1] for remaining rows starting with row 2
for (i in 2:nrow(temp)){
temp$y[i]<-temp$x[i]*temp$y[i-1]
}
#Store results in "dat"
dat$y[idx:(nrow(temp)+idx-1)]<-temp$y
idx<-nrow(temp)+1
rm(temp)
}