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.

 

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.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top