Possible Duplicate:
R sorts a vector on its own accord – bad boy!
How can I read the files in a directory in sorted order using R?
The code given below worked well. However, the problem is that when I typed dir1 to see the results I found that R order the files as:
[1] "data1.flt" "data10.flt" "data100.flt" "data101.flt"
[5] "data102.flt" "data103.flt" "data104.flt" "data105.flt"
[9] "data106.flt" "data107.flt" "data108.flt" "data109.flt"
[13] "data11.flt" "data110.flt" "data111.flt" "data112.flt"
[17] "data113.flt" "data114.flt" "data115.flt" "data116.flt"
.
.
to
.
.
[357] "data91.flt" "data92.flt" "data93.flt" "data94.flt"
[361] "data95.flt" "data96.flt" "data97.flt" "data98.flt"
[365] "data99.flt"
which will lead to wrong results.
How to tell R to start reading from 1 to 365 in order(I even used sort(dir1) but didn’t sort them).
something like :
[1] "data1.flt" "data2.flt" "data3.flt" "data4.flt"
not like:
[1] "data1.flt" "data10.flt" "data100.flt" "data101.flt"
Here is the code:
dir1 <- list.files("C:\\Users", "*.flt", full.names = TRUE)
results <- list()
for (.files in seq_along(dir1)){
file2 <- readBin(dir2[.files], double(), size = 4, n = w * 67420, signed = TRUE)
results[[length(results) + 1L]] <- file1[file1 != -9999]*10
}
for (i in seq_along(results)){
fileName <- sprintf("C:\\New folder (2)\\NewFile%03d.bin", i)
writeBin(as.integer(results[[i]]), fileName, size = 2)
}
If you know the structure of the name of your files you could use that instead of grabbing them directly from
dir.paste0was introduced in R 2.15 so for older versions you’ll need:Further edits because you seem to be confused. filename gets updated each iteration through the loop. You can see this by printing the filename each time.