Search code examples
rgisraster

Set single raster to NA where values of raster stack are NA


I have two 30m x 30m raster files which I would like to sample points from. Prior to sampling, I would like to remove the clouded areas from the images. I turned to R and Hijman's Raster package for the task.

Using the drawPoly(sp=TRUE) command, I drew in 18 different polygons. The function did not seem to allow 18 polygons as one sp object, so I drew them all separately. I then gave the polygons a proj4string matching the rasters', and set them into a list. I ran the list through a lapply function to convert them to rasters (rasterize function in Hijman's package) with the polygon areas set to NA, and the rest of the image set to 1.

My end goal is one raster layer with the 18 areas set to NA. I have tried stacking the list of rasterized polygons, and subsetting it to put set a new raster to NA in the same areas. My reproducible code is below.

library(raster)
r1 <- raster(nrow=50, ncol = 50)
r1[] <- 1
r1[4:10,] <- NA
r2 <- raster(nrow=50, ncol = 50)
r2[] <- 1
r2[9:15,] <- NA
r3 <- raster(nrow=50, ncol = 50)
r3[] <- 1
r3[24:39,] <- NA

r4 <- raster(nrow=50, ncol = 50)
r4[] <- 1

s <- stack(r1, r2, r3)

test.a.cool <- calc(s, function(x){r4[is.na(x)==1] <- NA})

For whatever reason, the darn testacool is a blank plot, where I'm aiming to have it as a raster with all values except for the NAs in the stack, s, equal to 1.

Any tips?

Thanks.


Solution

  • Doing sum(s) will work, as sum() returns NA for any grid cell with even one NA value in the stack.

    To see that it works, compare the figures produced by the following:

    plot(s)
    plot(sum(s))