# How to combine lists in R?

When we have multiple lists but they have similar type of data then we might want to combine or merge those lists. This will be helpful to use because we can perform the calculations using one list name instead of applying them on multiple ones. We can combine multiple lists with the help of mapply function.

## Example

Consider the below lists −

> List1<-list(letters[1:5],1:5,5:1,25,c("A","B","C","D"))
> List1
[[1]]
[1] "a" "b" "c" "d" "e"
[[2]]
[1]  1   2   3   4   5
[[3]]
[1]  5   4   3   2   1
[[4]]
[1] 25
[[5]]
[1] "A" "B" "C" "D"
> List2<-list(letters[6:10],6:10,c(25,16,9,4,1),36,c("Andy","Boston","Caroline","Dinesh"))
> List2
[[1]]
[1] "f" "g" "h" "i" "j"
[[2]]
[1]  6   7   8   9  10
[[3]]
[1] 25  16   9   4   1
[[4]]
[1] 36
[[5]]
[1] "Andy" "Boston" "Caroline" "Dinesh"
> mapply(c, List1, List2, SIMPLIFY=FALSE)
[[1]]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
[[2]]
[1]  1   2   3   4   5   6   7   8   9  10
[[3]]
[1]  5   4   3   2   1  25  16   9   4   1
[[4]]
[1] 25 36
[[5]]
[1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh"

Now suppose, we have one more list that is List3 then it can be combined in the same way as shown below −

> List3<-list(letters[11:15],11:15,c(6,7,8,9,10),49,c("Aaron","Betty","Corie","Donald"))
> List3
[[1]]
[1] "k" "l" "m" "n" "o"
[[2]]
[1] 11  12  13  14  15
[[3]]
[1]  6  7    8   9  10
[[4]]
[1] 49
[[5]]
[1] "Aaron" "Betty" "Corie" "Donald"
> mapply(c, List1, List2, List3, SIMPLIFY=FALSE)
[[1]]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o"
[[2]]
[1]  1   2  3    4   5   6   7   8   9   10  11  12  13  14  15
[[3]]
[1]  5   4  3    2   1  25  16   9   4    1   6   7   8   9  10
[[4]]
[1] 25  36  49
[[5]]
[1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh" "Aaron" "Betty" "Corie" "Donald"

Updated on: 11-Aug-2020

284 Views