sacvf sacvf - 7 months ago 29
R Question

How can I read the files in a directory in sorted order using R?

The code given below worked well and read the files in my directory and extracted the values:

X <- c(75:85) ; Y <- c(208:215)
extract <- vector()
files <- list.files("C:\\New folder (10)", "*.img",full.names=TRUE)


I tried to specify that by using sprintf but I got error. Any help please:

for (i in c(1:365)) {
fileName <- sprintf("C:New folder (10)/Climate_Rad_%d.img", i)


Why not retrieve all files (with a particular pattern) with list.files() and then sort that. Then you retrieve the files from the sorted vector, which gives them to you in correctly sorted order. This has the advantage that it also works when numbers are missing from the 1:365 sequence

Something like:

myFiles <- list.files(pattern = "^Climate_Rad_") #all files starting with Climate_
myFiles <- sort(myFiles)
# then read them in, for instance through
for (fileNames in myFiles) {READ.IN.AND.DO.YOUR.MAGIC.ON.THEM}