Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Natural sort order (human sort order) in R list.files()

Tags:

r

natural-sort

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.

like image 873
Iain S Avatar asked Jan 24 '13 07:01

Iain S


2 Answers

"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)]
like image 66
mbq Avatar answered Oct 06 '22 22:10

mbq


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])
like image 39
Miles Rout Avatar answered Oct 07 '22 00:10

Miles Rout