Skip to contents

Loops allow you to repeat the same thing again and again. If you are doing something more than two or three times, you should instead use a loop to avoid having to copy and paste the same code over and over again. Since duplicating code risks not only mistyping or not copying correctly, but also of creating confusion by filling your R scripts with nearly identical chunks of code. There are fundamentally two kinds of loop:

  • one where you know exactly how many times the loop will run, for instance because you’re running a chunk of code once for each element of a vector or row or column of a data frame; and
  • one where you do not, because some part of your calculation in each step of the loop will determine whether to continue or to stop.

for (...) loops

for loops allow us to repeat something for a fixed number of times (e.g. once per element of a vector, once per row of a data frame, etc.).

They are called as:

greetings <- c("Hello", "Goodbye")
for (word in greetings) {
  # body
}

and after each run through the loop, the variable (here word) is updated with the next element (here, in the vector greetings). We introduced for loops in week 1 and again in Lecture 5b and Practical A-1. They were then used from Practical 1-1 onwards.

There is a section in R4DS (within a more general chapter on Iteration) that covers for loops. For loops are also covered by R Coder here.

while (...) loops

while loops allows us to repeat something while a condition is still TRUE. They are particularly useful when you don’t know in advance exactly how many times something will be done, but can be used in any situation. Unlike for loops though, you need to update everything manually each time around:

test <- some_test()
while (test) {
  # Do something
  test <- update(something)
}

test is checked at the beginning of each iteration, and as long as test continues to be TRUE, the code block inside the curly brackets { ... } is run. Be careful… if you don’t update test inside the curly brackets, your loop will continue forever! However, if (when!) test is finally FALSE, the loop will end and R will continue on to the next line of code after the loop.

We introduced them in Lecture 6a, and used them from practical2-4 onwards. There is a section in R4DS (within a more general chapter on Iteration) that covers while loops. While loops are also covered by R Coder here.