How to combine two lists with the same structure in r

I have two lists, let's say

list1<-list(a=c(0,1,2),b=c(3,4,5));
list2<-list(a=c(7,8,9),b=c(10,11,12));

how to get a combined list how

list(a= rbind(c(0,1,2),c(7,8,9)), b = rbind(c(3,4,5),c(10,11,12)) )

I can do this for loops. Any other easier way to do this?

Thanks!

+4
source share
2 answers

I think this will work as a whole:

l<-lapply(names(list1),function(x) rbind(list1[[x]],list2[[x]]))
names(l)<-names(list1)

But if you can guarantee the same order in each list, this will work

mapply(rbind,list1,list2,SIMPLIFY=FALSE)
# $a
# [,1] [,2] [,3]
# [1,]    0    1    2
# [2,]    7    8    9
# 
# $b
# [,1] [,2] [,3]
# [1,]    3    4    5
# [2,]   10   11   12
+6
source

Using sapplywith simplify=FALSE, you will get free element names:

> sapply(names(list1),function(n){rbind(list1[[n]],list2[[n]])},simplify=FALSE)
$a
     [,1] [,2] [,3]
[1,]    0    1    2
[2,]    7    8    9

$b
     [,1] [,2] [,3]
[1,]    3    4    5
[2,]   10   11   12
+4
source

Source: https://habr.com/ru/post/1523602/


All Articles