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

Sort/reorder list by another list of the same length

I have two lists that I want two keep in list format.

list1 <- list("two", "one", "three")
list2 <- list(2, 1, 3)

I want to use list2 to reorder list1 while keeping both in list format. I would like the output of both lists to be as follows.

> list1
#[[1]]
#[1] "one"
#
#[[2]]
#[1] "two"
#
#[[3]]
#[1] "three"

> list2
#[[1]]
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] 3

How can I do this?

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

>Solution :

You can use order for this purpose; however, order expects a vector, so having list2 be a list is a bit inconvenient:

result = list1[order(unlist(list2))]
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