下面是我正在處理的一段代碼的簡化版本(爲避免混淆,省略了大量附加計算)。這只是cumsum
函數的修改形式。我不想重新發明輪子,這個功能是否已經存在?如果不是,什麼方案會提供最好的速度?修改後的cumsum函數
#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")
會你介意多解釋一下這是如何使用的?請注意''junk [1]'和'junk1 [1]'從未用於您的算法中...... – Tommy