Extract categorical raster values by polygons or hexagons
Source:R/extract_cat_raster.R
extract_cat_raster.Rd
Extracts categorical raster values (e.g., land cover classes) for each polygon in a given grid (e.g., H3 hexagons or administrative units). It returns either the proportion of each category within each polygon or the raw counts.
Arguments
- spat_raster_cat
A categorical raster of class `SpatRaster` from the **terra** package.
- sf_hex_grid
An object of class `sf` representing the polygons (e.g., hexagonal grid).
- proportion
Logical. If `TRUE` (default), returns the proportion of each category within each polygon. If `FALSE`, returns counts instead.
Value
An `sf` object with the extracted values joined to the input grid. Each polygon will contain the calculated proportions or counts of the categorical raster values that fall within its area.
Details
This function uses `exactextractr::exact_extract()` to accurately compute the overlap between polygons and raster cells. Invalid geometries are automatically fixed using `sf::st_make_valid()`, and only `POLYGON` or `MULTIPOLYGON` geometries are processed.
Examples
if (FALSE) { # \dontrun{
# Example categorical raster
r <- terra::rast(nrows = 10, ncols = 10)
terra::values(r) <- sample(1:3, terra::ncell(r), replace = TRUE)
# Example grid (hexagons)
bbox <- sf::st_as_sfc(sf::st_bbox(terra::as.polygons(r)))
hex <- sf::st_make_grid(bbox, cellsize = 0.2, square = FALSE)
hex_sf <- sf::st_sf(ID = 1:length(hex), geometry = hex)
# Extract proportions of land cover classes per hexagon
result <- extract_cat_raster(r, hex_sf, proportion = TRUE)
} # }