簡體   English   中英

如何根據另一個二進制文件中的類來計算幾個二進制文件中變量的平均值?

[英]How to calculate the averages of a variable in several binary files based on classes in another binary file?

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

要保存您編寫的文件:

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=""))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM