I'd like to filter a large raster, but only run the filter if the center cell of the window is a specific value. Essentially I'd like to remove some speckle (false positives) from an image (pixels of 0 or 1), but only run the filter if window center is 1.
# create some raster data
library(raster)
r <- raster(ncols=12, nrows=12)
set.seed(0)
r[] <- round(runif(ncell(r))*0.7 )
plot(r)
# custom filter
w=matrix(1,5,5)
gameOfLife <- function(x) {
f <- focal(x, w=w, pad=TRUE, padValue=0)
# window with with less than 5 cells die
x[f < 5] <- 0
# window with 5 or more cells live
x[f >= 5] <- 1
x
}
plot(gameOfLife(r))
The 2 circled cells, above, meet the criteria (having at least 5 values of 1 around them) but were initially a 0 and I want them to remain a 0. Thus, the filter only applies if the center value is already a 1.
Hope that makes sense. Many thanks in advance