Skip to content

Instantly share code, notes, and snippets.

@FlukeAndFeather
Last active July 30, 2019 03:29
Show Gist options
  • Save FlukeAndFeather/1f8d88096106445b2a24c9b831c94b7d to your computer and use it in GitHub Desktop.
Save FlukeAndFeather/1f8d88096106445b2a24c9b831c94b7d to your computer and use it in GitHub Desktop.
removing isolated cells from raster
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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment