Maral Dorri
Maral Dorri

Reputation: 478

Reorder dataframes in a list in r:

I have a list of data frames: my_list which contains 18 dataframes

> names(my_list)
 [1] "UG 100-12" "UG 100-15" "UG 100-9"  "UG 108-12" "UG 108-15" "UG 108-9"  "UG 116-12" "UG 116-15"
 [9] "UG 116-9"  "UG 124-12" "UG 124-15" "UG 124-9"  "UG 84-12"  "UG 84-15"  "UG 84-9"   "UG 92-12" 
[17] "UG 92-15"  "UG 92-9"

I want to reorder the list based on a vector of the names in the correct order:

df <- c("UG 84-9", "UG 84-12", "UG 84-15", "UG 92-9", "UG 92-12", "UG 92-15", "UG 100-9", 
        "UG 100-12", "UG 100-15", "UG 108-9", "UG 108-12", "UG 108-15", "UG 116-9", "UG 116-12", 
        "UG 116-15", "UG 124-9", "UG 124-12", "UG 124-15")

Any help would be appreciated. Thank you

Upvotes: 1

Views: 468

Answers (1)

hello_friend
hello_friend

Reputation: 5788

Base R solution:

my_ordered_list <- mylist[sort(names(mylist))]

Upvotes: 1

Related Questions