user3233418
user3233418

Reputation: 81

how to combine two lists with the same structure in r

I have two lists, 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 as

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

I can do it by for loops. Any other simpler way for this?

Thanks!

Upvotes: 8

Views: 5654

Answers (2)

Spacedman
Spacedman

Reputation: 94182

Using sapply with simplify=FALSE gets you the elements named for free:

> 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

Upvotes: 4

nograpes
nograpes

Reputation: 18323

I think this would work in general:

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

But if you could guarantee the same order in each list, this would 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

Upvotes: 10

Related Questions