Loops in R

Interactive R tutorial on loops: for over any vector, collect results, use while β€” and see when a vectorised one-liner replaces the loop entirely. Live in your browser.

Sometimes you need to repeat work. R has for and while loops β€” and, often, a vectorised one-liner that beats both. Edit and Run each box.

Watch: loops in 90 seconds

Every step below β€” for, while and the vectorised alternative β€” run live in RStudio, then try each one in the consoles that follow.

Download the R script  Β·  β–Ά Practice in the playground β€” or edit and run each snippet below.

A for loop runs once per element

Loop over any vector

The loop variable takes each value in turn β€” numbers or text:

Collect results in a vector

Create an empty vector first, then fill it position by position:

while repeats until the condition fails

Often you do not need a loop at all

R is vectorised β€” one line frequently replaces the whole loop:

Your turn


Next: The apply family β†’ β€” loops without writing loops.