aggregate_draws_to_polygons | R Documentation |
Aggregate grid cell draws to polygons using an aggregation table
aggregate_draws_to_polygons(
draws_matrix,
aggregation_table,
aggregation_cols = "polygon_id",
method = "mean",
z_dimension = NULL,
z_dimension_name = "z",
weighting_raster = NULL,
na.rm = TRUE
)
draws_matrix |
|
aggregation_table |
data.table::data.table Aggregation table linking pixels to
polygon identifiers, created using |
aggregation_cols |
(character vector, default 'polygon_id') Polygon identifiers
to use for aggregation. Must be field names within |
method |
(character, default 'mean') Aggregation method: one of 'mean', 'sum',
'weighted.mean', or 'weighted.sum'. The latter two methods require a
|
z_dimension |
(vector, default NULL) If passing a |
z_dimension_name |
(default 'z') The field name for the "z" dimension
corresponding to each layer of the |
weighting_raster |
(terra::SpatRaster, default NULL) The relative weighting of each whole pixel to the overall polygon value, for example, if calculating a population-weighted mean. Required for methods 'weighted.mean' and 'weighted.sum', ignored for the other methods. |
na.rm |
(bool, default TRUE) How to handle NA pixels in |
This is a more efficient and feature-rich alternative to terra's zonal statistics functions. Features include:
Always fractionally aggregate, weighting by area of the pixel in a polygon
Optionally weight by both area fraction and a weighting raster (e.g. population)
Means or sums of raster values across polygons
Optionally aggregate multiple years of raster data at once
data.table::data.table containing polygon identifiers, (optionally) layer
identifiers in the z_dimension_name
column, and data values aggregated by polygon.
build_aggregation_table
## Not run:
polygons <- sf::st_read(system.file('extdata/Benin_communes.gpkg', package = 'mbg'))
id_raster <- build_id_raster(polygons)
n_data_pixels <- sum(!is.na(terra::values(id_raster)))
# Example grid-level draws from e.g. mbg::generate_cell_draws_and_summarize()
draws_matrix <- matrix(rnorm(n_data_pixels * 5), nrow = n_data_pixels)
# Build aggregation table, which can be used across many aggregations
aggregation_table <- build_aggregation_table(
polygons, id_raster, polygon_id_field = 'commune_code'
)
# Aggregate the grid-level draws to polygon-level draws
aggregated <- aggregate_draws_to_polygons(
draws_matrix = draws_matrix,
aggregation_table = aggregation_table,
aggregation_cols = 'commune_code',
method = 'mean'
)
head(aggregated)
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.