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)]
精彩评论