How to Combine Lists in R (With Examples)


You can use either the c() function or the append() function to combine two or more lists in R:

#combine two lists using c()
combined <- c(list1, list2)

#combine two lists using append()
combined <- append(list1, list2)

Both functions will produce the same result.

The following examples show how to use this syntax in practice.

Example 1: Combine Two Lists

The following code shows how to combine two lists in R:

#define lists
list1 <- list(2, 5, 6, 8)
list2 <- list(A = 1:5, B = 3)

#combine two lists into one
combined <- c(list1, list2)

#view combined list
combined

[[1]]
[1] 2

[[2]]
[1] 5

[[3]]
[1] 6

[[4]]
[1] 8

$A
[1] 1 2 3 4 5

$B
[1] 3

We can also use the length() function to get the length of the combined list:

#get length of combined list
length(combined)

[1] 6

We can also use the class() function to get the class of the combined list:

#get class of combined list
class(combined)

[1] "list"

Example 2: Combine More Than Two Lists

We can use similar syntax to combine more than two lists in R:

#define lists
list1 <- list(2, 5, 6, 8)
list2 <- list(A = 1:5, B = 3)
list3 <- list(X = 'A', Y = 'B')

#combine three lists into one
combined <- c(list1, list2, list3)

#view combined list
combined

[[1]]
[1] 2

[[2]]
[1] 5

[[3]]
[1] 6

[[4]]
[1] 8

$A
[1] 1 2 3 4 5

$B
[1] 3

$X
[1] "A"

$Y
[1] "B"

Additional Resources

The following tutorials offer additional information about lists in R:

How to Create an Empty List in R
How to Append Values to List in R
How to Convert List to Matrix in R
How to Convert List to Vector in R

Leave a Reply

Your email address will not be published. Required fields are marked *