How to reclassify (subset) a raster r1
( of the same dimension and extent as r2
) based on following conditions in r2
in the given example.
Conditions:
- If the grid cells values of
r2
are>0.5
, retain corresponding value and adjacent 2 grids cells next to 0.5 values (ie buffer the grid cells with values>0.5
inr2
to the surrounding two grids in all directions) inr1
and change other values to 0.
ie. how can i change grid cells values in r1
such that it gives those values which correspond to >0.5
value grid cells and its buffering (surrounding) two grid cells in each direction in r2
.
If I only had to get grid cells >0.5
I would have easily obtained by the following code, however, I want to extract the >0.5
value as well as the value of the 2 surrounding gridcells as well.
Sample example calculation code is :
set.seed(150)
r1 <- raster(ncol=10, nrow=5) #Create rasters
values(r1) = round(runif(ncell(r1),5,25))
r2 <- raster(ncol=10, nrow=5)
values(r2) = round(runif(ncell(r2),0.1,1))
selfun <- function(x,y) {
ifelse( x >0.5, y,0)
} # It works only for >0.5 gridcells, i need this gridcells and its adjacent
#two gridcells in each direction.
# it's like buffering the >0.5 grid cells with adjacent two grids and retaining corresponding grid cells values.
r3<-overlay(r2,r1,fun=selfun)
plot(r3)
Thank you.