Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order list elements according to a vector

Say I have a list like:

my_list <- list(name1 = 'a', name2 = 'b', name3 = 'c', name4 = 'd')

And I want to order it according to the following variable:

my_var=c('name2','name1','name4','name3')

I tried the following, but does not work as I expect:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my_list[order(match(my_list, my_var))]
my_list[match(my_list, my_var)]

Any help? Thanks!

>Solution :

I guess you want to use match like this

> my_list[match(names(my_list), my_var)]
$name2
[1] "b"

$name1
[1] "a"

$name4
[1] "d"

$name3
[1] "c"

BUT, you already can simply run my_list[my_var] to achieve what you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading