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. Objectsrst1
andrst2
are replicates of the initial 'volcano' layer, and a random sample of n = 1000 cells inrst2
is set to NA. Afterwards,overlay
is applied and the associated function rejects all cells inrst1
that hold a valid value, i.e. different from NA, inrst2
.