R Save Results of Loop in Data Frame (Example Code)

In this R programming tutorial you’ll learn how to save for-loop outputs in data frames.

Example: Storing for-Loop Results in Data Frame

my_df <- data.frame(xxx = rep(NA, 10))                 # Some empty data
my_df                                                  # How the data looks like
#    xxx
# 1   NA
# 2   NA
# 3   NA
# 4   NA
# 5   NA
# 6   NA
# 7   NA
# 8   NA
# 9   NA
# 10  NA
for(index in 1:4) {                                    # Starting for-loop
  
  variable_new <- rep(paste0("V", index), 10)          # Create a new column
  
  my_df[ , index] <- variable_new                      # Append new column to data frame
  
  colnames(my_df)[index] <- paste0("Variable", index)  # Change column name
}
my_df                                                  # Data after loop
#    Variable1 Variable2 Variable3 Variable4
# 1         V1        V2        V3        V4
# 2         V1        V2        V3        V4
# 3         V1        V2        V3        V4
# 4         V1        V2        V3        V4
# 5         V1        V2        V3        V4
# 6         V1        V2        V3        V4
# 7         V1        V2        V3        V4
# 8         V1        V2        V3        V4
# 9         V1        V2        V3        V4
# 10        V1        V2        V3        V4

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.
You need to agree with the terms to proceed

Menu
Top