# install
install.packages("tidyverse") # cleaning data
install.packages("gt") # creating tablesfor Loops
Introduction
When working in R, you will often encounter situations where you need to perform the same task multiple times. For example, you might want to calculate the same statistic for several groups, apply the same transformation to multiple objects, or repeat an analysis using different inputs. Writing out the same code separately for every case can quickly become repetitive and difficult to maintain.
Loops provide a way to automate these repetitive tasks. A loop tells R to repeatedly execute a piece of code while changing the value being used each time. Rather than writing the same instructions over and over, you write them once and tell R which values you want to work through.
The goal of this vignette is to introduce the structure and logic of for loops in R and demonstrate how they can be used to automate repeated, multi-step tasks. We will begin by examining the basic components of a for loop, followed by more advanced applications, including nested loops, storing results, and repeatedly fitting models for different groups.
Finally, we will consider when a for loop is useful compared with vectorized or grouped approaches. By the end, you should be able to understand how for loops work, construct loops for your own analyses, and recognize situations where looping can make a repeated procedure easier to automate and manage.
R Packages
You will need the following R packages. If you have already installed them, skip the install.packages lines.
# load
library(tidyverse)
library(gt)for Loops
One of the most common types of loops is a for loop. for loops tell R to repeat the same piece of code for multiple items or values. We simply provide R with the code to be looped through and the collection of items (e.g., names) or values (e.g., years) to be iteratively passed through that code.
For example, suppose you want R to print each of the following numbers:
10
20
30
40
50You could write five separate print statements:
print(10)[1] 10
print(20)[1] 20
print(30)[1] 30
print(40)[1] 40
print(50)[1] 50
But this becomes inefficient when there are many values or when the code you want to repeat is more complicated.
A for loop allows you to accomplish the same task with a single line of code:
for (number in c(10, 20, 30, 40, 50)) {print(number)}[1] 10
[1] 20
[1] 30
[1] 40
[1] 50
The loop tells R: for each number in the collection c(10, 20, 30, 40, 50), print that number
The basic idea is simple, but understanding how each part of the loop works is important before using loops for more complicated tasks.
Basic Structure
A for loop has the following general structure:
for (item in vector) {code_to_repeat}where:
fortells R that you are creating a loopitemis an index variable that represents the current item in the loopvectoris the collection of values that R will work through- Typically stored using the
c(...)operator (see Vectors)
- Typically stored using the
code_to_repeatis the code to be looped through (i.e., the code that R repeats)- This code is always placed inside
{curly brackets}(see Code)
- This code is always placed inside
Looking again at the prior example:
for (number in c(10, 20, 30)) {print(number)}We see that number is the index variable, c(10, 20, 30) is the vector, and print(number) is the code to be repeated. R takes each value from the vector, assigns it to number, and then runs the code inside the {curly brackets}. In other words, R is performing the following steps:
# set `number` equal to 10 and print
number = 10
print(number)
# THEN BEGIN NEXT LOOP #
# set `number` equal to 20 and print
number = 20
print(number)
# THEN BEGIN NEXT LOOP #
# set `number` equal to 30 and print
number = 30
print(number)Vectors
The values that a loop works through are often stored in a vector. You can create a vector using the c() function.
numbers <- c(10, 20, 30, 40, 50)Here, the numbers 10, 20, 30, 40, and 50 are stored inside a vector called numbers. You can then use this vector in a loop:
for (number in numbers) {print(number)}[1] 10
[1] 20
[1] 30
[1] 40
[1] 50
This is equivalent to putting the vector directly inside the for statement:
for (number in c(10, 20, 30, 40, 50)) {print(number)}[1] 10
[1] 20
[1] 30
[1] 40
[1] 50
Vectors can contain different types of values, depending on what items you want used during your for loop. Above, we saw a for loop that iterates through a vector filled with numbers. But vectors can contain other type of values, too. The same basic logic applies regardless of what the vector contains.
# strings
colors <- c("red", "blue", "green", "yellow")
# logical values
answers <- c(TRUE, FALSE, TRUE, TRUE)And for loops can iterate over any of these:
for (color in colors) {print(color)}[1] "red"
[1] "blue"
[1] "green"
[1] "yellow"
for (answer in answers) {print(answer)}[1] TRUE
[1] FALSE
[1] TRUE
[1] TRUE
Index Variable
The variable immediately following for is called the index variable. In the for loop below, color is the index variable.
for (color in colors) {print(color)}The index variable is just a placeholder for the current item. The name given to the index variable (e.g., number or color) is not important. You may call it anything you like. It is simply a variable that takes on a specific value during each loop and passes that value onto your code.
What is important is that the index variable’s value changes with each iteration of the for loop.
# During the first iteration
color = "red"
# During the second iteration
color = "blue"
# During the third iteration
color = "green"
# During the fourth iteration
color = "yellow"What we call the index variable is irrelevant. The same for loop will produce identical output even as we change the name given to the index variable.
# index variable called "color"
for (color in colors) {print(color)}[1] "red"
[1] "blue"
[1] "green"
[1] "yellow"
# index variable called "item"
for (item in colors) {print(item)}[1] "red"
[1] "blue"
[1] "green"
[1] "yellow"
# index variable called "x"
for (x in colors) {print(x)}[1] "red"
[1] "blue"
[1] "green"
[1] "yellow"
In sum, what matters is that the index variable is used consistently inside the loop. What we call it is a matter of preference.
Code
The code between the {curly brackets} is what R will actually execute. Everything written here will be repeated for each item in the vector.
The code chunk below contains two lines of code within the loop. First, R will run print(number), followed by print(number * 2). R will run both lines for every value in the vector (i.e., 1, 2, and 3) when this loop is executed.
for (number in c(1, 2, 3)) {
# loop body
print(number)
print(number * 2)
}[1] 1
[1] 2
[1] 2
[1] 4
[1] 3
[1] 6
R first prints the value (print(number)) and then prints the value multiplied by 2 (print(number * 2)). The {curly brackets} are important because they tell R exactly which code belongs to the loop.
Nested for Loops
A single for loop can contain multiple additional for loops. This is called a nested loop. For example:
# outer loop
for (x in c(1, 2, 3)) {
# inner loop
for (y in c("A", "B")) {
print(paste(x, y))
}
}[1] "1 A"
[1] "1 B"
[1] "2 A"
[1] "2 B"
[1] "3 A"
[1] "3 B"
This can be read as, for each value in x (1, 2, and 3), and for each letter in y (A and B), print “x, y”.
With nested loops, the inner for function runs completely for each iteration of the outer for function. In other words, once the value of x is set (i.e., the outer loop), the inner loop runs for both values of y. Hence, we see that the output is “1 A”, “1 B”, “2 A”, “2 B”, and so forth.
Nested loops are useful when you need to work through combinations of two or more sets of values.
Storing Results
So far, our for loops have performed an operation and produced an output during each iteration. Oftentimes, we want to save the result from each iteration so that we can use all of the results after the loop has finished.
A common approach is to create an empty list before starting the for loop, and then add the result from each iteration to that list. Lists are particularly useful for storing more complex results, such as dataframes.
For example, suppose we want to calculate the square of several numbers. During each iteration, we can create a small dataframe containing the number and its square, and then store that dataframe in our list:
empty_list <- list() # create empty list
for (i in c(2, 4, 6, 8)) {
# perform operation
square <- i^2
# store result
empty_list[[i]] <- data.frame(iteration = i,
value = square)
}
# combine the results from each iteration
full_output <- bind_rows(empty_list)Here, each iteration produces a small dataframe containing two pieces of information: the value of i (named iteration in our dataframe) and its square (named value). The resulting dataframes are stored in empty_list. After the loop has finished, bind_rows combines the individual dataframes into a single dataframe called full_output. full_output contains one row for each iteration:
full_output |> gt() # `gt` simply prints the dataframe as a neat table.| iteration | value |
|---|---|
| 2 | 4 |
| 4 | 16 |
| 6 | 36 |
| 8 | 64 |
Storing results this way is particularly useful when each iteration involves multiple processing steps and produces a structured result. In the next section, we will use this approach to repeatedly perform a data analysis and combine the results from each iteration.
Applications
for loops are particularly useful when an analysis consists of multiple steps that need to be repeated for a series of inputs. For instance, you may want to fit the same statistical model separately for many groups.
We can demonstrate this using the iris dataset, which is included with R. The dataset contains measurements of 150 iris flowers belonging to three species (setosa, versicolor, and virginica).
table(iris$Species)
setosa versicolor virginica
50 50 50
head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
The variables include measurements of sepal length, sepal width, petal length, petal width, and species.
Suppose we want to examine the relationship between sepal length and petal length. We could fit one linear regression model using all of the observations:
# linear model
model1 <- lm(Petal.Length ~ Sepal.Length, data = iris)
# print coefficient
model1$coefficients (Intercept) Sepal.Length
-7.101443 1.858433
which tells us that, across all three species of iris flowers, a 1 centimeter increase in sepal length is associated with an estimated 1.86 centimeter increase in petal length, on average.
If we plot each of our 150 observations we can examine this relationship visually.
However, we might instead want to know what this relationship is for each of the individual species. To do so, we would fit three separate models. We saw above that the three iris species contained in the iris dataset are setosa, versicolor, and virginica. These names will become the items in our vector, and we will call our index variable species_name.
# create empty list to store out from each model
models <- list()
# fit a model for each species
for (species_name in c("setosa", "versicolor", "virginica")) {
# filter data to single species
species_data <- iris |> filter(Species == species_name)
# estimate model
model <- lm(Petal.Length ~ Sepal.Length, data = species_data)
# store results
models[[species_name]] <- model
}There are several steps inside this loop. For each of the three species in iris, R:
Selects the observations belonging to that species (using
filter)Fits a linear regression model (using
lm)Stores the resulting model inside a list (called
models)
The resultant models object is a list containing three items - the linear model outputs for each of the three iris species. In other words, each element of models is a complete R model object. We can then access each element using [[double brackets]]
# relationship between sepal and petal length for setosa species
models[["setosa"]]$coefficients (Intercept) Sepal.Length
0.8030518 0.1316317
# relationship between sepal and petal length for versicolor species
models[["versicolor"]]$coefficients (Intercept) Sepal.Length
0.1851155 0.6864698
# relationship between sepal and petal length for virginica species
models[["virginica"]]$coefficients (Intercept) Sepal.Length
0.6104680 0.7500808
By filtering the iris data by species and running separate linear models, we gain a much more nuanced understanding of the 1.86 coefficient obtained when modelling the full data. Specifically, we find that the average association between sepal and petal length is 0.13 for setosa, 0.69 for versicolor, and 0.75 for virginica.
When to use a for Loop
The iris example illustrates an important principle - you should not use a for loop simply because you need to perform an operation multiple times.
For example, if we only wanted to calculate the mean petal length for each species, we would be better off using the group_by function from tidyverse.
iris |>
# group the data by species
group_by(Species) |>
# return mean petal length within each group
summarize(mean_petal_length = mean(Petal.Length, na.rm = TRUE)) |>
# print output in clean table
gt()| Species | mean_petal_length |
|---|---|
| setosa | 1.462 |
| versicolor | 4.260 |
| virginica | 5.552 |
This is simpler than writing a for loop.
A for loop becomes more useful when each iteration involves a procedure rather than a single calculation. Some situations where loops can be useful include:
- Fitting a model separately for many groups
- Running a simulation many times
- Performing several processing steps on each input
- Using conditional logic during each iteration
- Storing complex objects such as models or plots
- Performing an operation where the result of one iteration affects the next
Thus, the key question is not do I need to do something more than once? but rather would repeating a sequence of operations with a loop make this analysis clearer or easier to automate?