Chapter 10. Loops, the Un-R Way to Iterate

When starting to use R, most people use loops whenever they need to iterate over elements of a vector, list or data.frame. While it is natural to do this in other languages, with R we generally want to use vectorization. That said, sometimes loops are unavoidable, so R offers both for and while loops.

10.1. for Loops

The most commonly used loop is the for loop. It iterates over an index—provided as a vector—and performs some operations. For a first simple example, we print out the first ten numbers.

The loop is declared using for, which takes one English-seeming argument in three parts. The third part is any vector of values of any kind, most commonly numeric or character. The first part is the variable ...

Get R for Everyone: Advanced Analytics and Graphics 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.