我有 5 个具有相同尺寸的二进制文件(栅格):前四个文件代表参数 1,第五个文件代表具有 10 个类别的土地覆盖图。我想根据土地覆盖类别计算所有四个文件的平均值。所以最后我们会得到每个类对应的4个值。
就像是:
1(first class):
first file = 0.5(average of all pixels correspond to class 1 from the land cover)
second file = 0.4(average of all pixels correspond to class 1 from the land cover)
third file = 0.2(average of all pixels correspond to class 1 from the land cover)
fourth file = 0.1(average of all pixels correspond to class 1 from the land cover)
2(second class):
first file = 0.5(average of all pixels correspond to class 2 from the land cover)
second file = 0.4(average of all pixels correspond to class 2 from the land cover)
third file = 0.2(average of all pixels correspond to class 2 from the land cover)
fourth file = 0.1(average of all pixels correspond to class 2 from the land cover
等等...
我在stackoverflow中发现了一些非常相似的东西:如何根据另一个二进制文件中的类计算一个二进制文件中变量的平均值?
然而,这在某种程度上是不同的,我有 4 个文件而不是一个文件。所以我需要在我的所有文件中循环该代码。
全部文件:
1-读取一个文件:
fre <- file("C:\\corr.bin","rb")
sdf<- readBin(fre, numeric(), size=4, n=1440*720, signed=TRUE)
2-阅读土地覆盖文件:
land <- file("C:\\land cover.bin","rb")
over<- readBin(land, integer(), size=1, n=1440*720, signed=F)
3-仅使用一个文件计算平均值:
result=tapply(sdf, over, mean, na.rm=TRUE)
我对所有文件都试过这个:
dir1<- list.files("C:\filesh", "*.img", full.names = TRUE)
fre <- file("C:\\landover_from Suj1440a.bin","rb")
sdf<- readBin(fre, integer(), size=1, n=1440*720, signed=F)
results<- list()
for (.files in seq_along(dir1)){
list1 <- readBin(dir1[.files], numeric(), size = 4, n = 1440*720, signed = TRUE)
list1=tapply(list1, sdf, mean, na.rm=TRUE)
results[[length(results) + 1L]]<- list1}
似乎它没有错误地工作。:写结果(来自kith回答):
for (i in seq_along(results)){
write.table(results[[i]], paste("C:\\filesh\\data", i, ".txt", sep=""))
我会得到4个文本文件data1,data2,data3,......
4-我感谢任何有关如何将所有结果写入一个文本文件的帮助。我希望输出是一个包含所有结果的文本文件:
class 1 2 3 4 5 6 7 ...
data1 0.2 0.5 0.2 . . . . ...
data2 0.1 0.5 0.6
data3 . . . . . . . ...
data4 .