I have a simple problem, but can’t find a straightforward answer for it. I have the following type of list
my.list=list(a=c(1,2,3),random=1,list=matrix(1:10,nrow=2))
of which I would like to change the order of list elements (here: 'a','random' and 'list') according to the order of another list ('a','list','random'), or thus a vector of list names: names(my.other.list):
my.other.list=list(a=c(4,5,6),list=matrix(101:110,nrow=2),random=2)
so the goal is to obtain this list:
my.wanted.list=list(a=c(1,2,3),list=matrix(1:10,nrow=2),random=1)
Note that both list (my.list and my.other.list) have the same list names, and that these can not be sorted alphabetically or so.
I created this loop:
my.wanted.list=list()
for(i in 1:length(my.list)){
my.wanted.list[[i]]=my.list[[names(my.other.list)[i]]]
}
names(my.wanted.list)=names(my.other.list)
But that seems like a time consuming solution for a seemingly simple problem. Especially if the lists are bigger. So is there a simpler way of doing this?
Thank you.