Skip to Content

Combine Two or More Lists Into One in R

Lists are used to store one-dimensional data in R. They are similar to vectors but they also have the flexibility to store values of different types which a vector doesn’t. When working with lists it can be handy to know how to combine lists together. In this tutorial, we will look at how to combine two or more lists into a single list in R with the help of some examples.

How to combine lists in R?

combine two lists in R using c() function

You can use the c() function in R to combine two or more lists into a single list. Pass the lists you want to combine as comma-separated arguments to the c() function. The following is the syntax –

# combine lists 
c(ls1, ls2, ls3, ...)

It returns a single combined list.

Examples

Let’s now look at some examples of combining some lists in R.

Combine two lists into a single list

First, let’s combine two lists with numeric values into a single list using the c() function.

# create two lists
ls1 <- list(1, 2, 3)
ls2 <- list(4, 5)
# combine lists
ls <- c(ls1, ls2)
# display the resulting list
print(ls)

Output:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

Here, we create two lists of numbers in R, ls1 and ls2, and then use the c() function to combine the two lists into a single list. You can see that the resulting list has elements from both the lists ls1 and ls2.

Note that since lists are ordered, the list resulting from c(ls1, ls2) will be different from the list resulting from c(ls2, ls1).

Combine more than two lists into a single list

You can similarly combine more than two lists into a single list using the c() function. This time let’s combine three lists with character values.

# create three lists
ls1 <- list("milk", "eggs")
ls2 <- list("butter", "cheese", "jam")
ls3 <- list("bread")
# combine lists
ls <- c(ls1, ls2, ls3)
# display the resulting list
print(ls)

Output:

[[1]]
[1] "milk"

[[2]]
[1] "eggs"

[[3]]
[1] "butter"

[[4]]
[1] "cheese"

[[5]]
[1] "jam"

[[6]]
[1] "bread"

Here we combine three lists containing some grocery items into a single list. You can see that the resulting list is a concatenation of the lists ls1, ls2, and ls3.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Authors

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.