Learn/R/5. Loops
Lesson 5 of 8
Sign in

R, lesson 5

Loops

A loop runs the same block of code several times. R has three kinds: for, while and repeat.

for: once per value

A for loop walks through a vector, giving the loop variable each value in turn:

To count, loop over a sequence. 1:5 is the vector 1 2 3 4 5, and seq(10, 0, by = -2) is 10 8 6 4 2 0:

There is a classic trap with 1:n. When n is 0, 1:0 is 1 0, a vector counting , so the loop runs twice instead of zero times. Use instead: it gives , and an empty vector when is 0.

2 exercises to try what you just read.

Exercise 1

Rocket countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Piggy bank

Press Ctrl Enter or Check to test your code.

down
seq_len(n)
1 2 … n
n

You can also loop over the lines you read from input: for (line in lines) { ... }.

while: as long as a condition holds

A while loop checks its condition before each round and stops when it becomes FALSE. Use it when you do not know in advance how many rounds you need:

Make sure something inside the loop moves the condition towards FALSE, or it will run forever.

break and next

  • break leaves the loop immediately.
  • next skips the rest of this round and moves on to the next one.

repeat { ... } loops forever until a break, which is useful when the stopping test belongs in the middle of the loop.

Building up a result

A common loop pattern keeps a running total. Start it before the loop and update it inside:

R can often do the same job without a loop (sum(c(2.5, 4, 1.25))), and you will see those vector tools in lesson 7. Loops are still the clearest choice when each step depends on the one before or when you need to stop early.

Further reading

  • An Introduction to R, section "Repetitive execution: for loops, repeat and while"
  • R documentation: Control flow

Read a whole number n (0 or more) and count down from n to 1, one number per line, then print Liftoff!. When n is 0, print only Liftoff!.

Sample input:

Sample output:

Each input line holds one coin value in cents. Add the coins up in order, but stop at the first line that is 0 (ignore it and everything after it). Print how many coins you counted and their total on two lines, in the form shown below. There is always at least the 0 line.

Sample input:

Sample output:

for (fruit in c("apple", "pear", "plum")) {
  cat("I like", fruit, "\n")
}
for (i in 1:3) {
  cat("Lap", i, "\n")
}
n <- 0
for (i in seq_len(n)) cat("never printed\n")
balance <- 100
years <- 0
while (balance < 200) {
  balance <- balance * 1.1
  years <- years + 1
}
cat("Doubled after", years, "years\n")
for (n in 1:10) {
  if (n %% 2 == 0) next   # skip even numbers
  if (n > 7) break        # stop completely after 7
  cat(n, "")
}
cat("\n")                  # prints: 1 3 5 7
total <- 0
for (price in c(2.5, 4, 1.25)) {
  total <- total + price
}
cat(total, "\n")   # 7.75
3
3
2
1
Liftoff!
50
20
5
0
100
Coins: 3
Total: 75 cents