Store Results of Loop in List in R (Example) | Save Output of while- & for-Loops

 

This tutorial illustrates how to save the output of a for-loop in a list object in R programming.

Table of contents:

Let’s jump right to the example!

 

Example: Saving for-Loop Output in List

In this Section, I’ll illustrate how to store the results of a for-loop in a list in R. First, we have to create an empty list:

my_list <- list()               # Create empty list
my_list                         # Print empty list
# list()

Now, we can write and run our for-loop as shown below. Within the loop, we are specifying a head (i.e. three iterations), some output for each iteration, and we are storing this output in our list:

for(i in 1:3) {                 # Head of for-loop
  output <- rep(i, 5)           # Output of iteration i
  my_list[[i]] <- output        # Store output in list
}

Let’s check out the final output list:

my_list                         # Print final list
# [[1]]
# [1] 1 1 1 1 1
# 
# [[2]]
# [1] 2 2 2 2 2
# 
# [[3]]
# [1] 3 3 3 3 3

As you can see based on the previous output of the RStudio console, we have created a list with three list elements.

 

Video, Further Resources & Summary

Would you like to know more about loops and lists? Then you may watch the following video of my YouTube channel. I’m explaining the topics of this article in the video:

 

The YouTube video will be added soon.

 

Furthermore, you could have a look at some of the related articles on my homepage. You can find a selection of articles here:

 

In this R tutorial you learned how to store the results created in a for-loop in a list. Let me know in the comments below, in case you have any additional questions.

 



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