Order List Items

I have a simple problem but cannot find a simple answer for it. I have the following list type

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 the list items (here: "a", "random" and "list") in accordance with the order of another list ("a", "list", "random"), or, thus, the vector list names: names (my.other.list):

 my.other.list=list(a=c(4,5,6),list=matrix(101:110,nrow=2),random=2) 

therefore, the goal is to get this list:

 my.wanted.list=list(a=c(1,2,3),list=matrix(1:10,nrow=2),random=1) 

Please note that both lists (my.list and my.other.list) have the same list names and that they cannot 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 this seems like a time-consuming solution to a seemingly simple problem. Especially if the lists are larger. So is there an easier way to do this?

Thanks.

+5
source share
1 answer

You can simply do this using the list subset mechanism with names.

 my.list=list(a=c(1,2,3),random=1,list=matrix(1:10,nrow=2)) my.other.list=list(a=c(4,5,6),list=matrix(101:110,nrow=2),random=2) 

no pakage

 my.list[names(my.other.list)] #> $a #> [1] 1 2 3 #> #> $list #> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 3 5 7 9 #> [2,] 2 4 6 8 10 #> #> $random #> [1] 1 

or you can use the package as rlist

 my.list %>% list.subset(names(my.other.list)) #> $a #> [1] 1 2 3 #> #> $list #> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 3 5 7 9 #> [2,] 2 4 6 8 10 #> #> $random #> [1] 1 

it will recode your first list in the order of the name vector that you use for the subset.

+10
source

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


All Articles