How to Add New Elements to a List in R (Example)

 

In this R programming tutorial you’ll learn how to append new elements to a list.

The post will contain the following topics:

Let’s take a look at some R codes in action:

 

Creation of Exemplifying Data

Let’s first create an example list for the example of this R programming tutorial:

my_list <- list(L1 = 1:5, L2 = "XXX")              # Create example list
my_list                                            # Print example list
# $L1
# [1] 1 2 3 4 5
# 
# $L2
# [1] "XXX"

Our list contains two list elements called L1 and L2.

Let’s also create a data object that we can append to our list later on:

my_element <- LETTERS[1:3]                         # Create example element
my_element                                         # Print example element
# "A" "B" "C"

Our example element is a vector consisting of three characters.

 

Example: Appending New List Element in R

Now, we can merge our example list with our example element. Have a look at the following R code:

my_list_new <- c(my_list, L3 = list(my_element))   # Add element to list
my_list_new                                        # Print updated list
# $L1
# [1] 1 2 3 4 5
# 
# $L2
# [1] "XXX"
# 
# $L3
# [1] "A" "B" "C"

As you can see based on the output of the RStudio console, we have created a new list consisting of the list elements of our original list plus the character vector that was contained in our example data object. Note that the added list element was named L3.

 

Video & Further Resources

Do you need more information on the R code of this tutorial? Then you might watch the following video of my YouTube channel. I show the R programming code of this tutorial in the video.

 

 

Furthermore, you might have a look at the other articles of www.statisticsglobe.com. I have released numerous other posts about the manipulation of lists already.

 

In summary: You learned in this post how to create and name new list elements in R. Please let me know in the comments, if you have additional questions.

 

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.


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.

Top