Skip to content

Instantly share code, notes, and snippets.

@obrl-soil
Last active November 22, 2016 06:43
Show Gist options
  • Save obrl-soil/94a1b2ce85ace0f4e4802ac1cba19473 to your computer and use it in GitHub Desktop.
Save obrl-soil/94a1b2ce85ace0f4e4802ac1cba19473 to your computer and use it in GitHub Desktop.
for calculating the mode of a focal window over a categorical raster
# for calculating the mode of a focal window over a categorical raster.
# Handling ties by retaining input cell value rather than default 'random'
winmode <- function(x) {
y <- modal(x, na.rm = T, ties = 'NA')
if (is.na(y)) { return(x[ceiling(length(x) / 2)]) } else {return(y)}}
# e.g.
# x <- raster(matrix(c(1:36), byrow = T, ncol = 6))
# f <- focal(x, w = matrix(1, ncol = 3, now = 3), fun = winmode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment