Search code examples
rraster

How to assign some values in Stack using independent raster?


I have several rasters. I stacked them all to do some calculations later, but I would like to assign some values in all layers to NA based on another raster.

the code:

library(raster)
r <- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
r1 <- raster(nrows=10, ncols=10)
r1 <- setValues(r1, 1:ncell(r))
r2 <- raster(nrows=10, ncols=10)
r2 <- setValues(r1, 1:ncell(r))
St=stack(r,r1)
St[r2>1]==NA
#         layer.1 layer.2
#  [1,]      NA      NA
#  [2,]      NA      NA
#  [3,]      NA      NA
#  [4,]      NA      NA
#  [5,]      NA      NA

But when I typed St I found that the min and max are 1 and 100 which means that the were not assigned to NA?

St
# class       : RasterStack 
# dimensions  : 10, 10, 100, 2  (nrow, ncol, ncell, nlayers)
# resolution  : 36, 18  (x, y)
# extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 
# names       : layer.1, layer.2 
# min values  :       1,       1 
# max values  :     100,     100 

Solution

  • It is just a typo. You should have said St[r2>1]<-NA instead of St[r2>1]==NA.