Set NA Cells in One Raster Where Another Has Values in R

rraster

I have two rasters in R. I want to set values to NA in the first raster where the second raster has values. I think this should be simple, using the raster package, with two RasterLayer objects raster1 and raster2, both the same extent and snapped to each other. They are 29775×29930.

I'm doing:

newraster <- raster1[is.na(raster2)]

But this seems to take an unnecessary amount of memory, and keeps crashing R. My computer has 8GB of memory. Is there a less memory-intensive way to do this?

Best Answer

This can easily be solved using the overlay function from the raster package. Objects rst1 and rst2 are replicates of the initial 'volcano' layer, and a random sample of n = 1000 cells in rst2 is set to NA. Afterwards, overlay is applied and the associated function rejects all cells in rst1 that hold a valid value, i.e. different from NA, in rst2.

library(raster)

rst <- raster::raster(volcano)
rst1 <- rst
rst2 <- rst

# artificial gaps
set.seed(123)
id <- sample(1:ncell(rst), 1000)
rst2[id] <- NA

# introduce na in rst1 for all locations that are non-na in rst2
rst1_mod <- overlay(rst1, rst2, fun = function(x, y) {
  x[!is.na(y[])] <- NA
  return(x)
})

plot(rst1_mod)

volcano_incl_na

Related Question