Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to combine two lists with the same structure in r

Tags:

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!

like image 858
user3233418 Avatar asked Jan 24 '14 20:01

user3233418


1 Answers

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
like image 159
nograpes Avatar answered Nov 15 '22 18:11

nograpes