Search code examples
rbinaryraster

How to replace values by NA in file 2 correspond to specified values in file 1?


I have two binary files(rasters) with the same dimensions. The first file is called over and the second is corr. I want to replace values in over by NA whenever corr is greater than 0.5.

  1. Read the first file:

    conn <- file("C:\\corr.bin", "rb")
    over <- readBin(conn, numeric(), size=4,  n=1440*720, signed=TRUE)
    y <- t(matrix((data=corr), ncol=720, nrow=1440))## binary
    r1 <- raster(t(matrix((data=over), ncol=720, nrow=1440)))## raster
    
  2. Read the second file:

    conne <- file("C:\\cor06.bin", "rb")
    corr <- readBin(conne, numeric(), size=4,  n=1440*720, signed=TRUE)
    y1 <- t(matrix((data=corr), ncol=720, nrow=1440))## binary
    r <- raster(t(matrix((data=corr), ncol=720, nrow=1440)))##raster
    
  3. Write the results:

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

Solution

  • It's tricky to see exactly what you want, but what about:

    over[corr > 0.5] = NA
    

    or something a bit more complicated:

    over[corr < 0.2 | corr > 0.4] = NA