Reputation: 1655
In a directory with 100 files (001.csv, 002.csv, ..., 100.csv), I want to load a range of selected files, e.g., file 30 to 50 (030.csv, 031.csv, ..., 050.csv).
One way is:
allFiles = list.files(directory)
csvFiles <- file.path(directory, allFiles[30:50])
dataFrames <- lapply(csvFiles, read.csv)
This method seemed to work. But I still have question:
class(allFiles)
[1] "character"
allFiles is a character of length 100. How to know the file names will be sorted in ascending order, so that 030.csv is in 30th, 050.csv is in 50th position, not any others?
Any other methods to read a selected range of files in R?
Upvotes: 0
Views: 150
Reputation: 667
One way to do it is just to use sort: allFiles <- sort(allFiles)
.
But in general, I would recommend listing the files explicitly. You can do this as follows:
useFiles <- paste0(sprintf("%03d",30:50),".csv")
csvFiles <- file.path(directory, useFiles)
This way if someone adds another file to the directory later, your code is robust.
Upvotes: 3