๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R For Loop

A for loop runs a block once for each value in a sequence. The loop variable takes each value in turn.

Run over a number run

The loop variable takes each number from 1 to 5. Each round prints the current number.

for (n in 1:5) {
  print(n)
}

Run over day names

The loop variable takes each day name in turn. Each round prints one name.

for (day in c("Mon", "Tue", "Wed")) {
  print(day)
}

The last value stays

The loop prints each number from 1 to 3. A final print shows the loop variable still holds 3.

for (n in 1:3) {
  print(n)
}
print(n)

Example

total <- 0
for (n in 1:4) {
  total <- total + n
}
print(total)

Key points

  • The word in joins the loop variable to its values.
  • The colon symbol builds a run of numbers such as 1 to 5.
  • The values after in decide how many rounds run.
  • A for loop suits a known set of values.
  • The loop variable keeps its last value after the loop ends.

In this example, the loop runs once for each number from 1 to 4. Each round adds the loop variable to total, and print shows 10.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does the loop variable hold after a loop over 1 to 3 finishes?