29
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 #combine two lists using append()
combined
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
list2
#combine two lists into one
combined #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
list2
#combine three lists into one
combined #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