3

可能的重复:
R 自行对向量进行排序 - 坏孩子!
如何使用 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)
} 
4

2 回答 2

7

因为它不解释数字——而是对字符串进行排序

于 2012-05-28T14:44:29.090 回答
4

如果您知道文件名称的结构,则可以使用它而不是直接从dir.

for(i in seq(365)){
    filename <- paste0("data", i, ".flt")
    # Do some stuff with filename
}

paste0在 R 2.15 中引入,因此对于旧版本,您需要:

for(i in seq(365)){
    filename <- paste("data", i, ".flt", sep = "")
    # Do some stuff with filename
}

进一步的编辑,因为你似乎很困惑。文件名通过循环在每次迭代中更新。您可以通过每次打印文件名来看到这一点。

for(i in seq(365)){
    filename <- paste("data", i, ".flt", sep = "")
    print(filename)
    # Do some stuff with filename
}
于 2012-05-28T14:51:06.627 回答