rlist

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)

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"