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

Is there a simple way to sort files in natural order (otherwise known as human order), i.e. file9.csv is preceded by file10.csv? list.files () does not seem to have parameters for the sort order.

There are many implementations in other languages ​​(for example, here ) and Rosetta Code has only solutions in C, Perl, Python, etc.

+4
source share
3 answers

"Human varieties" is an illusion of a mad man, available only to hypothetical AI systems, but only with proper contextual knowledge.

To do this, you should use some quick regular expression to extract metadata from file names and use them to organize files:

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

You can try to name 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]) 
+1
source

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

0
source

All Articles