How to Do More with Loops in R - dummies

How to Do More with Loops in R

By Andrie de Vries, Joris Meys

R contains some of the mechanisms used in other programming languages to manipulate loops:

  • The keyword next, to skip to the next iteration of a loop without running the remaining code in the code block

  • The keyword break, to break out of a loop at any given point

  • The keyword while, to construct a loop that continues as long as a certain condition is TRUE.

You find more information on the use of these keywords on the Help page ?Control.

Although you can technically use all three options, they’re not often used. Many programmers consider the use of break and next to be bad coding practice in any language.

For while, the situation is a bit more complex. A while loop is useful only in very specific cases, like when you generate artificial data that has to meet certain conditions or when you write your own optimization algorithms. But in many cases the built-in optimization functions like optim(), optimize(), and nlm() work faster than a while loop — and often more stable. These functions require a bit of study before you can apply them, but studying the Help pages ?optim, ?optimize, and ?nlm, as well as related pages, can really pay off.