R Save Results of Loop in List (Example Code)

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

Example: Storing Results of for-Loop in List

list_object <- list()                 # Creating empty list object
for(index in 1:5) {                   # Start of for-loop
  
  my_out <- rep(LETTERS[index], 3)    # Creating some output
  
  list_object[[index]] <- my_out      # Saving result of iteration
}
list_object                           # Printing updated list
# [[1]]
# [1] "A" "A" "A"
# 
# [[2]]
# [1] "B" "B" "B"
# 
# [[3]]
# [1] "C" "C" "C"
# 
# [[4]]
# [1] "D" "D" "D"
# 
# [[5]]
# [1] "E" "E" "E"

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