Below is a simplified version of a segment of code that I’m working on (a lot of additional calculations are left out to avoid confusion). It’s just a modified form of the cumsum function. I don’t want to re-invent the wheel, so does this function already exist? If not, what scheme would provide the best speed?
#Set up the data
set.seed(1)
junk <- rnorm(1000000)
junk1 <- rnorm(1000000)
cumval <- numeric(1000000)
#Initialize the accumulator
cumval[1] <- 1
#Perform the modified cumsum
system.time({
for (i in 2:1000000) cumval[i] <- junk[i] + (junk1[i] * cumval[i-1])
})
#Plot the result
plot(cumval, type="l")
This algorithm is something that fits the
compilerpackage perfectly!…so it would be interesting to know if this algorithm is in any way “typical” – in that case the compiler could perhaps be even more optimized for situations like this…