The Dreaded for Loop
r-help discussion listserv for R often has questions about how to accomplish various tasks without
for loops. There seems to be a feeling that programmers should avoid these loops at all costs. Those who pose the queries usually have the goal of speeding up their code.
It’s important to understand that simply rewriting code to avoid loops will not necessarily make the code faster. However, in some cases, dramatic speedup may be attained, usually through vectorization.
Vectorization for Speedup
Sometimes, you can use vectorization instead of looping. For example, if
y are vectors of equal lengths, you can write this:
z <- x + y
This is not only more compact, but even more important, it is faster than using this loop: ...