R – How to Remove Pixel Completely in Stack If One Layer Contains NA Values

rrasterstack

I have a raster stack of soil temperatures from the year 2000 to 2020. I have previously cleaned out the individual layers if they exceeded the overall mean +/- 2 std.dev. by

stacked <- stack("path/soiltemp.tif")

# calculate a mean raster
mean <- calc(stacked, fun = mean)

# make a new raster as standard deviation of stacked rasters
sd <- calc(stacked, fun = sd)

upper = mean + (sd*2)
lower = mean - (sd*2)

result = stack()

for(i in 1:nlayers(stacked)){
  sub = stacked[[i]]
  sub[sub == 0] = NA
  sub[sub > upper] = NA
  sub[sub < lower] = NA
  result = stack(result, sub)
  print(i)}

I would like to delete/set to NA for the pixels that contain at least one layer of NA values.

How can I loop through the layers and set the whole stack to NA, if one layer contains NA values?

Best Answer

The easy way out was to simply do the following:

m <- mask(stacked, calc(stacked, fun = sum))