Search code examples
rrasterterrarasterstats

Mask layer of a raster stack using other layer using terra


I have a raster stack of 145 rasters. If there is NA in any of the layers for a specific cell(s), I want to set that cell to be NA in all the other layers. I devised a way to do it below, but I'm not sure it's very efficient. I would appreciate ideas on a better way?

library(terra)
a <- rast(ncol = 2, nrow = 2)
values(a) <- c(1,2,3,4)
names(a) <- "layer_one"

b <- rast(ncol = 2, nrow = 2)
values(b) <- c(1,2,3,4)
names(b) <- "layer_two"

c <- rast(ncol = 2, nrow = 2)
values(c) <- c(1,2,3,NA)
names(c) <- "layer_three"

z <- c(a,b,c)

my_layer_mask <- app(z, mean)

masked_z <- mask(z, my_layer_mask)

values(masked_z)

     layer_one layer_two layer_three
[1,]         1         1           1
[2,]         2         2           2
[3,]         3         3           3
[4,]        NA        NA          NA

Solution

  • I am not sure if this is more efficient, but it is perhaps a bit clearer:

    m <- any(is.na(z)) 
    masked_z <- mask(z, m, maskvalue=TRUE)
    

    With "terra" version 1.6-19 you can use anyNA

    masked_z <- mask(z, anyNA(z), maskvalue=TRUE)