替换for循环

Xu *_*ang 1 performance for-loop r vectorization

我想找到一种方法来替换我正在使用的for循环.我的问题的快速版本是:我如何从矢量[a,b,c,d,e]转到[1,a,a*b,a*b*c,a*b*c*d]?我目前做的事情如下:

myvec <- c(.3,.5,.2,.3,.3)  
new_vec <- vector(length=length(myvec))  
new_vec[1] <- 1  
for (i in 2:length(myvec)) {  
    new_vec[i] <- myvec[i-1]*new_vec[i-1]  
}  
Run Code Online (Sandbox Code Playgroud)

但是,这非常慢.有任何想法吗?谢谢!

And*_*son 5

这样做你想要的吗?

c(1, cumprod(myvec))[1:length(myvec)]
Run Code Online (Sandbox Code Playgroud)