Merge Two Lists in R (Example)
This page shows how to merge two lists in the R programming language.
Note that this article aims to merge two lists (i.e. if the elements of both lists have the same name the two elements will be combined). In case you want to know how to append lists, you may have a look here.
However, the table of contents of this tutorial looks as follows:
Let’s dive right into the R code.
In the following example, I’m going to use two example lists. The first list looks as follows…
list1 <- list(A = "A1", B = "B1", C = "C1") # Create first example list list1 # Print first example list # $A #  "A1" # # $B #  "B1" # # $C #  "C1"
…and the second list looks as follows:
list2 <- list(A = "A2", B = "B2", C = "C2") # Create second example list list2 # Print second example list # $A #  "A2" # # $B #  "B2" # # $C #  "C2"
As you can see, both lists contain the same element names, but the values within each element are different.
Now, let’s join these two lists in R…
Example: Merge Two Lists in R
We can use the Map function to combine our lists as follows:
list12 <- Map(c, list1, list2) # Merge two lists list12 # Print merged list # $A #  "A1" "A2" # # $B #  "B1" "B2" # # $C #  "C1" "C2"
As you can see, the elements with the same element name in both lists were combined into a single list element (i.e. A1 of list1 and A2 of list2 were combined).
Note that both lists need to have the same element names in order to make this R code work.
Video, Further Resources & Summary
Do you want to know more about the merging of multiple lists in R? Then you might watch the following video of my YouTube channel. In the video, I’m explaining the R programming codes of this article in RStudio:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Also, you might want to read some of the other tutorials of my homepage. A selection of articles can be found below:
- Append Lists in R
- Merge Data Frames by Column Name
- How to Add New Elements to a List
- R Functions List (+ Examples)
- The R Programming Language
Summary: In this tutorial, I showed how to combine list elements with the same name in the R programming language. In case you have any further questions, tell me about it in the comments.
Statistics Globe Newsletter