Search code examples
rraster

How to assign all values to NA with condition?


library(raster)
r1 <- r2 <- r3 <- raster(ncol=10, nrow=10)
r1[] <- runif(ncell(r1))
r2[] <- runif(ncell(r2)) / 2
r3[] <- runif(ncell(r3)) * 1.5
s <- stack(r1, r2, r3)


 r11 <- r22 <- r33 <- raster(ncol=10, nrow=10)
 r11[] <- runif(ncell(r11))
 r22[] <- runif(ncell(r22)) / 2
 r33[] <- runif(ncell(r33)) * 1.5
 g <- stack(r11, r22, r33)

If any pixel in g is >= 5, make the corresponding pixel in s = NA

which can be done like this:

  s[g >= 5]= NA

but also all time series of this pixel in s = NA


Solution

  • Let's do this with "terra" (the replacement of "raster").

    Example data

    library(terra)
    set.seed(0)
    s <- rast(ncol=10, nrow=10, nlyr=3, vals=rep(1:100, 3))
    g <- rast(ncol=10, nrow=10, nlyr=3, vals=sample(8, 300, replace=TRUE))
    

    Set all values in s to NA if a cell in g is larger than or equal to 5 in any of its layers.

    g5 <- any(g >= 5)  
    x <- mask(s, g5, maskvalue=1)