library(raster)
#> Loading required package: sp
# Create a random raster
set.seed(10)
foo <- raster(matrix(round(runif(100)), 10, 10))
# Add up neighbors
# NOTE: won't do anything about cells on the raster edge
foo_focal <- focal(foo, w = matrix(1, 3, 3), fun = sum)
# Set an isolation threshold
threshold <- 4
# Copy original raster and remove isolates
foo2 <- foo
foo2[foo_focal < threshold + 1] <- 0
# Plot side-by-side
opar <- par(mfrow = c(1,2))
plot(foo)
plot(foo2)
par(opar)
Created on 2019-07-29 by the reprex package (v0.3.0)