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 list of lists based on nth integer in list name in R?

Say I have a list of lists with list names that differ by the last integer in the name.

gfit10_3 <- list(1,1,1)
gfit10_1 <- list(1,1,1)
gfit10_2 <- list(1,1,1)
gfit10_10 <- list(1,1,1)

list1 <- list(gfit10_3=gfit10_3, gfit10_1=gfit10_1, gfit10_2=gfit10_2, gfit10_10=gfit10_10)

How do I order the list in ascending order based on the list name so the list would look like this?

list1 <- list(gfit10_1, gfit10_2, gfit10_3, gfit10_10)

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 try this alternative:

new_order <- order(as.numeric(sub(".*_(\\d+)", "\\1",names(list1))))
list1[new_order]

The list would be sorted by this order:

> names(list1)[new_order]
[1] "gfit10_1"  "gfit10_2"  "gfit10_3"  "gfit10_10"
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