list.files in R
1
0
Entering edit mode
3.0 years ago
arsa ▴ 20

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?

R • 2.3k views
ADD COMMENT
1
Entering edit mode

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?

ADD REPLY
0
Entering edit mode

Why not just use the file that has the file names?

ADD REPLY
0
Entering edit mode

I mean I have a folder. Sorry for my mistake

ADD REPLY
1
Entering edit mode
3.0 years ago
v.grozdanov ▴ 10

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"

ADD COMMENT

Login before adding your answer.

Traffic: 1800 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6