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


In this article you’ll learn how to save the results of a loop in a data frame in R.

The article will consist of this information:

If you want to learn more about these topics, keep reading:


Example: Saving output of for-Loop in Data Frame

This Example explains how to store the results of a for-loop in a data frame.

First, we have to create a data frame with the number of rows that our final data frame will have. The following R code creates such a data frame and fills the cells with NA values. This initial data frame needs to have only one column, since this data is overwritten later on.

data <- data.frame(NA_col = rep(NA, 3))     # Creating data containing NA
data                                        # Printing data
#   NA_col
# 1     NA
# 2     NA
# 3     NA

Now, we can write a for-loop that saves its results in our data frame. The following R code runs a for-loop with five iterations. In each iteration a new column is created, added to our data frame, and renamed.

for(i in 1:5) {                             # Head of for-loop
  new_col <- rep(i, 3)                      # Creating new variable
  data[ , i] <- new_col                     # Adding new variable to data
  colnames(data)[i] <- paste0("Col_", i)    # Renaming new variable

Have a look at the final output:

data                                        # Printing updated data
#   Col_1 Col_2 Col_3 Col_4 Col_5
# 1     1     2     3     4     5
# 2     1     2     3     4     5
# 3     1     2     3     4     5

As you can see based on the previous output of the RStudio console, we have created a data frame consisting of three rows and five numeric columns. Each column contains the output of one iteration of our for-loop.

Note that we could use the same type of R code within while-loops or repeat-loops.


Video & Further Resources

I have recently published a video on my YouTube channel, which illustrates the R syntax of the present post. You can find the video below.


The YouTube video will be added soon.


In addition, you might want to have a look at the other articles on my website. I have published several articles about loops in R already.


This page illustrated how to save for-loop outputs in data frames in R. In case you have any additional questions, let me know in the comments section below.


Subscribe to the Statistics Globe Newsletter

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

4 Comments. Leave new

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.