aggregate_to_polygons: Aggregate gridded data to polygon regions

View source: R/spatial.R

aggregate_to_polygonsR Documentation

Aggregate gridded data to polygon regions

Description

Assigns each grid cell to a polygon, then aggregates the values of the cells in each polygon. The spatial match uses only the distinct cells. Thus, a daily series with many dates does not make the match slower.

Usage

aggregate_to_polygons(
  data,
  polygons,
  value_col,
  method = c("nearest_centroid", "point_in_polygon"),
  polygon_id_cols = NULL,
  agg_fun = function(x) mean(x, na.rm = TRUE),
  by = NULL,
  fill_empty = FALSE
)

Arguments

data

Data frame with longitude, latitude, and value columns

polygons

sf object with polygon geometries (CRS 4326)

value_col

Name of the column to aggregate, or a character vector of names. Give names to set the result columns, for example c(tmean = "temp_c"). A column without a name keeps its name.

method

Aggregation method: "nearest_centroid" (each polygon gets the cell nearest to a point on its surface) or "point_in_polygon" (each polygon gets the cells in it)

polygon_id_cols

Character vector of column names to use as polygon identifiers. The default is all the columns of polygons except the geometry.

agg_fun

Aggregation function. It gets the values of one group, which can include NA. The default is the mean without the NA values.

by

Optional character vector of more group columns in data, for example "date". The result then has one row for each polygon and each value of by.

fill_empty

For "point_in_polygon": if TRUE, a polygon with no cell in it (smaller than a cell) gets the cell nearest to a point on its surface.

Value

Data frame with the polygon identifiers, the by columns and the aggregated values. It has one row for each polygon and each value of by. A polygon with no cell has NA.

Examples

grid <- expand.grid(longitude = seq(72.5, 77.5, by = 1), latitude = seq(18.5, 21.5, by = 1))
grid$temperature <- seq_len(nrow(grid))
cells <- sf::st_make_grid(sf::st_as_sfc(sf::st_bbox(
  c(xmin = 72, ymin = 18, xmax = 78, ymax = 22),
  crs = 4326
)), n = c(2, 1))
polys <- sf::st_sf(region = c("west", "east"), geometry = cells)
aggregate_to_polygons(grid, polys, value_col = "temperature")

varunayan documentation built on Oct. 30, 2026, 1:07 a.m.