Loop Through List in R (Example) | while- & for-Loop Over Lists
In this R programming tutorial you’ll learn how to run a for-loop to loop through a list object.
The tutorial looks as follows:
Let’s start right away:
Introduction of Example Data
Let’s first create some example data in R:
my_list <- list(c(6, 1, 5, 4, 1), # Create example list "XXXX", letters[1:3]) my_list # Print example list # [[1]] # [1] 6 1 5 4 1 # # [[2]] # [1] "XXXX" # # [[3]] # [1] "a" "b" "c"
The previous output of the RStudio console shows the structure of our example data – It’s a list consisting of three different list elements.
Example: for-Looping Over List Elements in R
In this Example, I’ll explain how to loop through the list elements of our list using a for-loop in R. Within each iteration of the loop, we are printing the first entry of the corresponding list element to the RStudio console:
for(i in 1:length(my_list)) { # Loop from 1 to length of list print(my_list[[i]][1]) # Printing some output } # [1] 6 # [1] "XXXX" # [1] "a"
This example has shown how to loop over a list using a for-loop. However, it would also be possible to loop through a list with a while-loop or a repeat-loop.
Video, Further Resources & Summary
Have a look at the following video of my YouTube channel. I explain the examples of this tutorial in the video.
The YouTube video will be added soon.
Also, you might read some of the other articles on this website.
- Store Results of Loop in List
- Append to List in Loop
- for-Loop in R
- Loops in R
- The R Programming Language
To summarize: In this article, I showed how to loop over list elements in R. Don’t hesitate to tell me about it in the comments below, if you have further questions or comments.
2 Comments. Leave new
for(i in 1:length(my_list)) { # Loop from 1 to length of list
print(my_list[[i]][1]) # Printing some output
}
what does the i represent, and the one in the second line ” print(my_list[[i]][1]) “
Hi Ted,
I’m sorry for the delayed reply. I was on a long vacation, so unfortunately I wasn’t able to get back to you earlier. Do you still need help with your syntax?
Regards,
Joachim