문제

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])

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top