2
votes

Suppose that I have data frames named df1 to df20. These data frames are in a list.

The order of the data fame in the list is "df1", "df10", "df11", "df12", How do I make it to become "df1", "df2", "df3", "df4", ?

3

3 Answers

3
votes

Create a vector of names and subset them. If the list is called dflist.

dflist <- dflist[paste0('df', 1:20)]

Can also use gtools::mixedsort.

dflist <- dflist[gtools::mixedsort(names(dflist))]
2
votes

Package stringr functions str_sort and str_order have an argument numeric that when set to TRUE sorts numerically. Here are two ways, assuming the data.frames list is named dflist.

dflist <- dflist[stringr::str_sort(names(dflist), numeric = TRUE)]

i <- stringr::str_order(names(dflist), numeric = TRUE)
dflist <- dflist[i]
0
votes

You can remove the string df in the names of the list using sub, cast the result to integer using as.integer and use the output of order to get the wanted order in the list.

dflist <- dflist[order(as.integer(sub("df", "", names(dflist))))]

Alternatively you can remove all non digits using \\D in gsub.

dflist <- dflist[order(as.integer(gsub("\\D", "", names(dflist))))]