list.files in R
I have a folder with file names like:
T0_1_xxx.csv
T0_2_xxx.csv
T5_1_xxx.csv
T5_2_xxx.csv
T10_1_xxx.csv
T10_2_xxx.csv
mapped.files <- list.files(pattern = ".csv")
mapped.files gives me:
T0_1_xxx.csv
T0_2_xxx.csv
T10_1_xxx.csv
T10_2_xxx.csv
T5_1_xxx.csv
T5_2_xxx.csv
I think R is basically sorting here. How can I undo this sort and just get the original ordering as in the file?
• 3,279 views
•
link
1 answer
As seidel correctly pointed out, what you see as 'original' ordering depends on many factors so it's not optimal to rely on it without explicitly speciying order.
Still if you need a 'natural' sorting of the numeric components you can use str_sort with numeric=TRUE from stringr/tidyverse:
stringr::str_sort(list.files(), num = TRUE)
[1] "T0_1_xxx.csv" "T0_2_xxx.csv" "T5_1_xxx.csv" "T5_2_xxx.csv" "T10_1_xxx.csv" "T10_2_xxx.csv"
• 0 views
•
link
Log in to answer this question.
Why not just use the file that has the file names?
I mean I have a folder. Sorry for my mistake
The docs mention that files are returned in alphabetical order. However, what do you mean by the "original ordering" in the directory? The order in which one sees files in a directory can depend on many things such as OS, file system, and whatever process is showing you the filenames. It's risky to depend on any given order, unless you're using explicit means to dictate the order. Why not spell out the order you need? Maybe you need them by creation time? You can read file attributes using
file.info(). What, exactly, determines the order you need?