Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Last active December 12, 2024 10:27
Show Gist options
  • Save h-a-graham/75a20ad7781cfe8ad13ba40dfead1368 to your computer and use it in GitHub Desktop.
Save h-a-graham/75a20ad7781cfe8ad13ba40dfead1368 to your computer and use it in GitHub Desktop.
aggregate a categorical raster - yielding a band for each class with the proportion of cover for the class
library(terra)
#> terra 1.8.0

# create example landcover raster
r <- rast(
  extent = c(0, 15000, 0, 15000),
  resolution = 30,
  crs = "+proj=laea"
)
values(r) <- sample(1:4, ncell(r), replace = TRUE)

plot(r)

prop_aggregate <- function(x, target_res) {
  terra::project(
    terra::segregate(x), terra::crs(x),
    method = "average", res = target_res
  )
}

r2 <- prop_aggregate(r, 1000)

plot(r2)

sum(r2)
#> class       : SpatRaster 
#> dimensions  : 15, 15, 1  (nrow, ncol, nlyr)
#> resolution  : 1000, 1000  (x, y)
#> extent      : 0, 15000, 0, 15000  (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=laea +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs 
#> source(s)   : memory
#> name        : sum 
#> min value   :   1 
#> max value   :   1

Created on 2024-12-12 with reprex v2.1.1

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