For your specific example the cumprod
function is one simple way to do this:
a <- c(1, rep(1.2, 20) )
a <- cumprod(a)
More generally if there is not a cum
function for your procedure, but you want that type of functionality then you can also use the Reduce
function:
a <- c(1, rep(1.2, 20))
a <- Reduce(`*`, a, accumulate=TRUE)
But consider that while there is a certain elegance in avoiding loops in R, from a practical standpoint the loop may be the quickest overall answer (when you include both programming and running time). Loops in R have been optimized to run reasonably fast (unless you create a really poor loop, but yours is an example of the efficient way to do things) and often if you can think of the looping approach then the time saved by vectorizing may be less than the extra time to think about how to vectorize it. Unless this is going to be done many times for very long loops, time savings may be too small to matter (see fortune(98)
). In the cases of very long vectors, rounding may be different between the for
loop and vectorized alternatives, so that issue may be of more importance than the speed.
Learning alternatives to for
are great for improving your knowledge/programming skills and can be great simplifiers for a lot of code, just don't feel that you always have to find an alternative to for
.