啊,好的,我明白了,问题出在排序上。排序顺序按字母顺序正确。Climate_Rad_1 按字母顺序后跟 Climate_Rad_10,而不是 Climate_Rad_2 顺序根本不是“随机”的,它按字母顺序是正确的。
但是,您希望在 Climate_Rad_10 之前处理 Climate_Rad_2,而不是之后。有几种方法可以解决这个问题。首先,您应该注意,Climate_Rad_002 确实按字母顺序排在 Climate_Rad_010 之前,因此如果您在生成文件时添加前导零,这将便于以后按数字顺序处理文件。
或者,假设您在创建文件时无法添加零。然后至少有两种方法可以按顺序访问文件。或者通过在文件名之后添加零,或者只是对文件名的数字部分进行排序。
让我告诉你后者。
myFiles <- paste("Climate_Rad_", c(1:15, 95:110), ".img", sep = "") # create some test names, you get the actual myFiles through a call to list.files()
myFiles.sorted <- sort(myFiles) # this gives the alphabetic sorting, not what you want
> myFiles.sorted
[1] "Climate_Rad_1.img" "Climate_Rad_10.img" "Climate_Rad_100.img"
[4] "Climate_Rad_101.img" "Climate_Rad_102.img" "Climate_Rad_103.img"
[7] "Climate_Rad_104.img" "Climate_Rad_105.img" "Climate_Rad_106.img"
[10] "Climate_Rad_107.img" "Climate_Rad_108.img" "Climate_Rad_109.img"
[13] "Climate_Rad_11.img" "Climate_Rad_110.img" "Climate_Rad_12.img"
[16] "Climate_Rad_13.img" "Climate_Rad_14.img" "Climate_Rad_15.img"
[19] "Climate_Rad_2.img" "Climate_Rad_3.img" "Climate_Rad_4.img"
[22] "Climate_Rad_5.img" "Climate_Rad_6.img" "Climate_Rad_7.img"
[25] "Climate_Rad_8.img" "Climate_Rad_9.img" "Climate_Rad_95.img"
[28] "Climate_Rad_96.img" "Climate_Rad_97.img" "Climate_Rad_98.img"
[31] "Climate_Rad_99.img"
# split between the part that comes before the numerics and the "1.img" etc.--adjust appropriately
split <- strsplit(myFiles.sorted, "Climate_Rad_")
# strip the "1.img" etc such that only the numeric part is left
# turn the characters in numeric
split <- as.numeric(sapply(split, function(x) x <- sub(".img", "", x[2])))
# not you can sort, by using order, that gives the original filenames, ordered on the numeric part of the filename
myFiles.correct.order <- myFiles.sorted[order(split)]
[1] "Climate_Rad_1.img" "Climate_Rad_2.img" "Climate_Rad_3.img"
[4] "Climate_Rad_4.img" "Climate_Rad_5.img" "Climate_Rad_6.img"
[7] "Climate_Rad_7.img" "Climate_Rad_8.img" "Climate_Rad_9.img"
[10] "Climate_Rad_10.img" "Climate_Rad_11.img" "Climate_Rad_12.img"
[13] "Climate_Rad_13.img" "Climate_Rad_14.img" "Climate_Rad_15.img"
[16] "Climate_Rad_95.img" "Climate_Rad_96.img" "Climate_Rad_97.img"
[19] "Climate_Rad_98.img" "Climate_Rad_99.img" "Climate_Rad_100.img"
[22] "Climate_Rad_101.img" "Climate_Rad_102.img" "Climate_Rad_103.img"
[25] "Climate_Rad_104.img" "Climate_Rad_105.img" "Climate_Rad_106.img"
[28] "Climate_Rad_107.img" "Climate_Rad_108.img" "Climate_Rad_109.img"
[31] "Climate_Rad_110.img"
这将按照您要查找的顺序为您提供文件。现在根据那个拉文件,例如通过
for (fileNames in myFiles.correct.order) {READ.IN.AND.DO.YOUR.THING}
那应该这样做。确保根据文件名调整“Climate_Rad_”和“.img”(您可能还必须在“Climate_Rad_”之前添加一个路径,使其类似于“C:/filefolder/Climate_Rad_”,如果是这样的话需要)。