Combine the two raster layers by setting the NA values ​​in the unscaled layer to 0, where the mask layer is not NA

I have two raster layers that I want to merge into one. We will call them mask(with the values 1and NA) and vrs.

library(raster)
mask <- raster(ncol=10, nrow=10)
mask[] <- c(rep(0, 50), rep(1, 50))
mask[mask < 0.5] <- NA
vrs <-raster(ncol=10, nrow=10)
vrs[] <- rpois(100, 2)
vrs[vrs >= 4] <- NA

I want to combine two large layers, but everything is fine for understanding these small examples. I want to make the pixel values ​​of my output layer be zero for those pixels where the masklevel 1and vrs- NA. All other pixels must remain with the original values vrs.

This is my only thought on how:

zero.for.NA <- function(x, y, filename){
  out <- raster(y)
  if(canProcessInMemory(out, n = 4)) { #wild guess..
    val <- getValues(y) #values
    NA.pos <- which(is.na(val)) #positiones for all NA-values in values-layer
    NA.t.noll.pos<-which(x[NA.pos]==1) #Positions where mask is 1 within the 
                                       #vector of positions of NA values in vrs
    val[NA.pos[NA.t.noll.pos]] <- 0 #set values layer to 0 where condition met
    out <- setValues(out, val)
    return(out)
  } else { #for large rasters the same thing by chunks
    bs <- blockSize(out)
    out <- writeStart(out, filename, overwrite=TRUE)
    for (i in 1:bs$n) {
      v <- getValues(y, row=bs$row[i], nrows=bs$nrows[i])
      xv <- getValues(x, row=bs$row[i], nrows=bs$nrows[i])
      NA.pos <- which(is.na(v))
      NA.t.noll.pos <- which(xv[NA.pos]==1)
      v[NA.pos[NA.t.noll.pos]] <- 0
      out <- writeValues(out, v, bs$row[i])
    }
    out <- writeStop(out)
    return(out)
  }
}

, , . / ? ? , , !

+4
2

cover():

r <- cover(vrs, mask-1)
plot(r)

enter image description here

+2

overlay:

r <- overlay(mask, vrs, fun=function(x, y) ifelse(x==1 & is.na(y), 0, y))

enter image description here

0

All Articles