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.
"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)]
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With