Skip to content

Instantly share code, notes, and snippets.

@johnbaums
Last active September 5, 2019 06:46
Show Gist options
  • Save johnbaums/17a8e732fd49bd82cbf8cd318a0b9858 to your computer and use it in GitHub Desktop.
Save johnbaums/17a8e732fd49bd82cbf8cd318a0b9858 to your computer and use it in GitHub Desktop.
Fill no data cells with focal mean/median
# Fill nodata within n x n cell window of cells that have data.
# Note that this can result in blocks n x n homogeneous blocks
# of a particular value extending out from a corner.
library(raster)
library(magrittr)
n <- 5 # width and height of window (in cells)
# note that n = 5 means that cells within 2 cells of a data cell
# will be affected (think of the focal cell as being in the middle
# of the n x n matrix, and the matrix defining the neighbourhood).
# define weights matrix - uniform weights within window
m <- matrix(1, n, n)
set.seed(1)
r <- raster(matrix(NA, 50, 50))
r[sample(ncell(r), 10)] <- 1
w <- distance(r)
i <- Which(is.na(r), cells=TRUE)
r[sample(i, 1000, replace=TRUE, prob=exp(-w[i]/2000))] <- 1
r[r==1] <- sample(5, sum(r[], na.rm=TRUE), replace=TRUE)
p <- rasterToPolygons(init(r, function(x) 1))
# raw raster
plot(r, axes=FALSE, box=FALSE)
plot(p, add=T, border='#00000050')
# Cells within n x n window of data cells.
# These are the cells that will be filled.
r2 <- focal(r, m, function(x) any(!is.na(x)), pad=TRUE)
r2[!is.na(r)] <- 2
plot(r2, axes=FALSE, box=FALSE)
plot(p, add=T, border='#00000050')
# focal mean
focal_mean <- focal(r, m, mean, na.rm=TRUE, NAonly=TRUE, pad=TRUE)
plot(focal_mean, axes=FALSE, box=FALSE)
plot(p, add=T, border='#00000050')
# focal median
focal_median <- focal(r, m, median, na.rm=TRUE, NAonly=TRUE, pad=TRUE)
plot(focal_median, axes=FALSE, box=FALSE)
plot(p, add=T, border='#00000050')
# plot all
#png('fillnodata.png', 8, 8, units='in', res=300)
stack(list(raw=r, to_fill=r2, mean=focal_mean, median=focal_median)) %>%
plot(axes=FALSE, box=FALSE,
addfun=function(x) plot(p, add=T, border='#00000050'))
#dev.off()
@johnbaums
Copy link
Author

fillnodata

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