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.
You could simply do this using the subsetting mechanism of list 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)
without any package
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 could use a 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 reoder your first list in the order of the name vector you use for subsetting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With