开发者

replacing a for-loop

开发者 https://www.devze.com 2023-03-15 15:38 出处:网络
I would like to find a way to replace a for loop that I am using. Quick version of my question is: how can I go from a vector [a,b,c,d,e] to [1,a,a*b,a*b*c,a*b*c*d] ?

I would like to find a way to replace a for loop that I am using. Quick version of my question is: how can I go from a vector [a,b,c,d,e] to [1,a,a*b,a*b*c,a*b*c*d] ? I currently do something like:

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]  
开发者_如何转开发}  

However, this is extremely slow. Any ideas? Thank you!


Does this do what you want?

c(1, cumprod(myvec))[1:length(myvec)]
0

精彩评论

暂无评论...
验证码 换一张
取 消