Add New Element to List in for-Loop in R (Example Code)

In this article you’ll learn how to concatenate new list elements in loops in the R programming language.

Example: Adding New Element to List in for-Loop

list_object <- list(1:7,
                    c("AAA", "Hello", "B"),
                    5,
                    LETTERS[8:4])
list_object                                    # Print example list
# [[1]]
# [1] 1 2 3 4 5 6 7
# 
# [[2]]
# [1] "AAA"   "Hello" "B"    
# 
# [[3]]
# [1] 5
# 
# [[4]]
# [1] "H" "G" "F" "E" "D"
for(index in 1:2) {                            # Starting for-loop
  list_object_new <- rep(letters[index], 5)    # Defining new element for list
  list_object[[length(list_object) + 1]] <-    # Adding new element to list
    list_object_new
}
list_object                                    # Returning new list to console
# [[1]]
# [1] 1 2 3 4 5 6 7
# 
# [[2]]
# [1] "AAA"   "Hello" "B"    
# 
# [[3]]
# [1] 5
# 
# [[4]]
# [1] "H" "G" "F" "E" "D"
# 
# [[5]]
# [1] "a" "a" "a" "a" "a"
# 
# [[6]]
# [1] "b" "b" "b" "b" "b"

Leave a Reply

Your email address will not be published.

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