Search code examples
rbinaryraster

How to calculate the averages of a variable in one binary file based on classes in another binary file?


I have two binary files(raster) with the same dimensions: the first represents correlation between 2 data and the second represents land cover map with 10 classes.I want take the average of my correlations based on the land cover classes. So finally we will got a map as the same as land cover map but with averages of correlations instead of the classes numbers.

Here are the two files:

  1- to read the first file correlation map:

   conne <- file("C:\\corr.bin","rb")
  corr<- readBin(conne, numeric(), size=4,  n=1440*720, signed=TRUE)
  y<-t(matrix((data=corr), ncol=720, nrow=1440))
    r = raster(y)

2- to read the second file land cover map:

  conne <- file("C:\\land cover.bin","rb")
  over<- readBin(conne, integer(), size=1,  n=1440*720, signed=F)
  y1<-t(matrix((data=over), ncol=720, nrow=1440))
  r1 = raster(y1)

3-to write the results:

     to.write = file(paste("/orcomplete.bin",sep=""),"wb")
     writeBin(as.double(results), to.write, size = 4)

Solution

  • Wouldn't this just be something like:

     tapply(y, y1, mean, na.rm=TRUE)
    

    If you want the class mean associated with the same arrangement as the input matrices then do this:

    outmat <- matrix( ave( y, y1, FUN=mean, na.rm=TRUE), nrow(y), ncol(y) )