How to Combine Lists in R (2 Examples)

 

This article shows how to append two lists in the R programming language.

The content of the page looks as follows:

Let’s start right away!

 

Construction of Example Data

For the example of this tutorial, we need to create two lists. Our first example list is created by the following R code…

list1 <- list(A = "A1", B = "B1", C = "C1")   # Create first example list
list1                                         # Print first example list
# $A
# [1] "A1"
# 
# $B
# [1] "B1"
# 
# $C
# [1] "C1"

…and our second list is created by the following R code:

list2 <- list(X = 1:3, Y = 10:5)              # Create second example list
list2                                         # Print second example list
# $X
# [1] 1 2 3
# 
# $Y
# [1] 10  9  8  7  6  5

Now, let’s combine these two lists into only one list…

 

Example 1: Append Two Lists in R with c() Function

If we want to combine two lists in R, we can simply use the c() function:

list12 <- c(list1, list2)                     # Merge two lists
list12                                        # Print merged list
# $A
# [1] "A1"
# 
# $B
# [1] "B1"
# 
# $C
# [1] "C1"
# 
# $X
# [1] 1 2 3
# 
# $Y
# [1] 10  9  8  7  6  5

As you can see based on the output printed to the RStudio console, we just combined our two example lists.

Often, R users think that the c() function can only be applied to single values or vectors. However, as you have seen based on the previous example, the c() function can also be applied to lists.

 

Example 2: Append Two Lists in R with append() Function

In Example 2 I’ll show an alternative to the c() function – the append() function. We can apply the append command to combine multiple lists as follows:

append(list1, list2)                         # Apply append function in R

Check your RStudio console output – It will be exactly the same as in Example 1.

 

Video & Further Resources

If you need further info on the topics of this tutorial, you might want to have a look at the following video of my YouTube channel. I’m explaining the R codes of this tutorial in the video tutorial:

 

 

In addition, you might want to have a look at the related articles of my homepage:

 

To summarize: At this point you should know how to concatenate two list objects in the R programming language. In case you have any additional questions or comments, please let me know in the comments.

 

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