Append to List in Loop in R (Example) | Add Element in while- & for-Loops

 

In this R post you’ll learn how to add new elements to a list within a for-loop.

The tutorial will contain this information:

Let’s dive into it.

 

Creation of Example Data

Have a look at the following example data:

my_list <- list("XXX",                             # Create example list
                letters[1:4],
                5:3)
my_list                                            # Print example list
# [[1]]
# [1] "XXX"
# 
# [[2]]
# [1] "a" "b" "c" "d"
# 
# [[3]]
# [1] 5 4 3

As you can see based on the previous output of the RStudio console, our example data is a list object consisting of three list elements.

 

Example: Adding New Element to List in for-Loop

This Example shows how to add new elements to the bottom of our example list using a for-loop.

Within each iteration of the for-loop, we are defining a new list element and we are appending this element to the bottom of our list.

Have a look at the following R code:

for(i in 1:3) {                                    # Head of for-loop
  new_element <- rep(i, 3)                         # Create new list element
  my_list[[length(my_list) + 1]] <- new_element    # Append new list element
}

Now, we can have a look at the updated list:

my_list                                            # Print updated list
# [[1]]
# [1] "XXX"
# 
# [[2]]
# [1] "a" "b" "c" "d"
# 
# [[3]]
# [1] 5 4 3
# 
# [[4]]
# [1] 1 1 1
# 
# [[5]]
# [1] 2 2 2
# 
# [[6]]
# [1] 3 3 3

As you can see based on the previous output of the RStudio console, we concatenated three new list elements to our list.

Note that we could apply a similar R syntax within while-loops and repeat-loops as well.

 

Video & Further Resources

I have recently published a video instruction on my YouTube channel, which explains the R code of this tutorial. You can find the video below:

 

The YouTube video will be added soon.

 

In addition, you might have a look at the other tutorials that I have published on this website:

 

You learned in this tutorial how to concatenate new list elements in loops in the R programming language. Don’t hesitate to let me know in the comments, if you have further questions. Furthermore, please subscribe to my email newsletter in order to get updates on the newest tutorials.

 

Subscribe to my free statistics newsletter

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


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