Home > other >  Masking raster with another raster
Masking raster with another raster

Time:06-01

I have a raster image with both numerical values and also NA's and would like to use it as a mask to remove values in a different raster. Does the raster package allow for this?

Example:

Raster A originally had values ranging from 0-1. I applied a raster calculation so that if values are <0.6, then they are transformed to NA. The resulting raster is a mix of values from 0.6 to 1 and NA's. I want to use Raster A to "mask" values from Raster B (Raster B values range from 0 to 1 also) so that if the value in Raster A = NA, then the same cell in Raster B = NA and if the cell in Raster A has a value of 0.6 to 1, then keep the corresponding cell value in Raster B. Any ideas?

CodePudding user response:

One option is to use overlay with the two rasters. Here, I first create two sample rasters using the volcano dataset. Then, I randomly assign NAs to the first raster (rst1). Then, apply overlay to change the cells in rst2 to NAs for those that match the NA cells in rst1.

library(raster)

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

# Assign some random cells NAs in rst1.
set.seed(123)
id <- sample(1:ncell(rst), 1000)
rst1[id] <- NA

# Assign NA to the cells where NA is present in rast1.
rst2_mod <- overlay(
  rst2,
  rst1,
  fun = function(x, y) {
    x[is.na(y[])] <- NA
    return(x)
  }
)

plot(rst2_mod)

Output

enter image description here

Another option is to just use calc (using rst1 and rst2 from above). We can stack the two raster layers, then change the cell to NA if there are any NAs present for that cell.

s.new <-
  raster::calc(
    raster::stack(rst2, rst1),
    fun = function(x)
      if (sum(is.na(x)) > 0)
        x * NA
    else
      x
  )

plot(s.new)

enter image description here

CodePudding user response:

You can use mask for masking:

Example data

library(terra)
B <- rast(system.file("ex/elev.tif", package="terra"))
set.seed(0)
A <- ifel(init(B, runif) > 0.6, NA, B)

Solution

x <- mask(B, A)
  • Related