Loops in R

This article will introduce loops in R and why they are useful as a basic programming structure. We will learn to use loops to iterate through data structures and to execute code a set number of times or based on a condition.

A loop is a control structure in programming where the instructions are written once, but a computer can execute them multiple times. Each execution of those instructions is called an iteration. Loops are commonly used in programming because, compared to repeated lines of code, they save time, reduce error, and are easy to read.

A loop allows a set of steps to repeat, either with a predefined number of repetitions or with a condition that keeps the loop going.

There are two types of loops in R: for loops and while loops. For loops repeat a piece of code for a known number of iterations, and a while loop repeats while a condition holds true.

For loops

Using for loops, you can tell a piece of code to run a defined X number of times or to iterate through the length of a data structure. The for loop requires a variable or counter that keeps track of where the current iteration is.

When we know an exact number of times we want the code to repeat, we can set up our for loop to count from 1 to X, and the code will stop executing after the Xth iteration. Below, we show the basic outline of a for loop that has a counter. We need the for keyword, a loop_variable to serve as the counter, the in keyword, and a range of 1 to number_of_iterations. We refer to the code inside of the curly { } brackets as the body of the loop.

for (loop_variable in 1:number_of_iterations) { # execute this code }

loop_variable can be used inside the loop if the number of the current iteration affects the code inside, but the variable only has meaning inside the loop. If you try to use that variable outside the loop, you’ll get an error.