如何根据另一个二进制文件中的类计算几个二进制文件中变量的平均值?

时间:2013-03-11 15:45:42

标签: r

我有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            .

1 个答案:

答案 0 :(得分:1)

要保存您编写的文件:

for (i in seq_along(results)){
    write.table(results[[i]], "C:\\filesh\\data%03d.txt", sep="\t")
}

你的意思是:

for (i in seq_along(results)){
    write.table(results[[i]], paste("C:\\filesh\\data", i, ".txt", sep=""))