Table of Contents
In R, there are several ways to loop through a list. The most common are the for loop, the while loop, and the apply family of functions. The for loop is used to iterate over each item in a list, the while loop is used to loop through a list while a condition is true, and the apply functions are used to apply a function to each item in a list. Each of these looping approaches has its own advantages and disadvantages, and can be used to efficiently and effectively loop through a list.
You can use one of the following methods to loop through a list in R:
Method 1: Loop Through List & Display All Sub-Elements on Same Line
for (i in my_list) { print(i) }
Method 2: Loop Through List & Display All Sub-Elements on Different Lines
for (i in my_list) {
for(j in i)
{print(j)}
}
Method 3: Loop Through List & Only Display Specific Values
#only display first value in each element of list
for(i in 1:length(my_list)) {
print(my_list[[i]][1])
}
The following examples show how to use each of these methods with the following list in R:
#create list
team_info <- list(team = 'Mavericks',
positions = c('G', 'F', 'C'),
all_stars = 3)
#view list
team_info
$team
[1] "Mavericks"
$positions
[1] "G" "F" "C"
$all_stars
[1] 3
Example 1: Loop Through List & Display All Sub-Elements on Same Line
The following code shows how to loop through the list and display each sub-element on the same line:
#print each sub-element on same line
for (i in team_info) {
print(i)
}
[1] "Mavericks"
[1] "G" "F" "C"
[1] 3
Notice that each sub-element is printed on the same line.
Example 2: Loop Through List & Display All Sub-Elements on Different Lines
The following code shows how to loop through the list and display each sub-element on different lines:
#print each sub-element on different lines
for (i in team_info) {
for(j in i)
{print(j)}
}
[1] "Mavericks"
[1] "G"
[1] "F"
[1] "C"
[1] 3
Notice that each sub-element is printed on its own line.
Example 3: Loop Through List & Only Display Specific Values
The following code shows how to loop through the list and display each sub-element on different lines:
#only display first value in each element of list
for(i in 1:length(team_info)) {
print(team_info[[i]][1])
}
[1] "Mavericks"
[1] "G"
[1] 3
Notice that only the first value in each element of the list is displayed.
Note: Simply change the [1] to display a different value in each element. For example, you could use [2] to display only the second value in each element.
The following tutorials explain how to perform other common operations in R: