The Dreaded for Loop

The 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.[5] 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 x and 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: ...

Get The Art of R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.