可能重复:
R sorts a vector on its own accord - bad boy!
How can I read the files in a directory in sorted order using R?
下面给出的代码效果很好。但问题是,当我输入dir1来查看结果时,我发现R将文件命令为:
[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"
会导致错误的结果。 如何告诉R按顺序从1到365开始读取(我甚至使用了sort(dir1)但没有对它们进行排序)。 类似的东西:
[1] "data1.flt" "data2.flt" "data3.flt" "data4.flt"
不喜欢:
[1] "data1.flt" "data10.flt" "data100.flt" "data101.flt"
以下是代码:
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)
}
答案 0 :(得分:6)
因为它不解释数字 - 而是排序字符串
答案 1 :(得分:4)
如果您知道文件名称的结构,可以使用它而不是直接从dir
抓取它们。
for(i in seq(365)){
filename <- paste0("data", i, ".flt")
# Do some stuff with filename
}
R 2.15中引入了 paste0
,因此对于旧版本,您需要:
for(i in seq(365)){
filename <- paste("data", i, ".flt", sep = "")
# Do some stuff with filename
}
进一步编辑因为你似乎很困惑。 filename通过循环每次迭代都会更新。您可以通过每次打印文件名来查看。
for(i in seq(365)){
filename <- paste("data", i, ".flt", sep = "")
print(filename)
# Do some stuff with filename
}