Question

Is there a simple way to sort files in natural order (otherwise known as human order), i.e. file9.csv comes before file10.csv? list.files() seems to have no options for the sort order.

There are plenty of implementations in other languages (e.g. here) , and Rosetta Code only has solutions in C, Perl, Python, etc.

Was it helpful?

Solution

"Human sort" is a mad man's illusion available only on hypothetical AI systems, but only when having proper context knowledge.

To this end you should rather use some quick regexp to extract meta-data from file names and use them to order files:

files<-c("file9.txt","file10.txt");
as.numeric(gsub('^file([0123456789]*)\\.txt$','\\1',files))->fileNum;
files[order(fileNum)]

OTHER TIPS

You could try naming it as file09.csv...

filenames <- paste0("file", 0:20, ".txt")
new_filenames <- sub("file([[:digit:]])\\.txt", "file0\\1\\.txt", filenames)
is_different <- new_filenames != filenames
file.rename(filenames[is_different], new_filenames[is_different])

You can use mixedsort() or mixedorder() from package gtools, as pointed out by @baptiste in the comments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top