Compute zonal statistics, that is summarize values of a SpatRaster for each "zone" defined by another SpatRaster, or by a SpatVector with polygon geometry.
If fun is a true R function, the <SpatRaster,SpatRaster> method may fail when using very large SpatRasters, except for the functions ("mean", "min", "max", "sum", "isNA", and "notNA").
You can also summarize values of a SpatVector for each polygon (zone) defined by another SpatVector.
z: SpatRaster with cell-values representing zones or a SpatVector with each polygon geometry representing a zone. z can have multiple layers to define intersecting zones
fun: function to be applied to summarize the values by zone. Either as character: "mean", "min", "max", "sum", "isNA", and "notNA" and, for relatively small SpatRasters, a proper function
...: additional arguments passed to fun, such as na.rm=TRUE
w: SpatRaster with weights. Should have a single-layer with non-negative values
wide: logical. Should the values returned in a wide format? For the SpatRaster, SpatRaster method this only affects the results when nlyr(z) == 2. For the SpatRaster, SpatVector method this only affects the results when fun=table
as.raster: logical. If TRUE, a SpatRaster is returned with the zonal statistic for each zone
filename: character. Output filename (ignored if as.raster=FALSE
overwrite: logical. If TRUE, filename is overwritten
wopt: list with additional arguments for writing files as in writeRaster
weights: logical. If TRUE and y has polygons, the approximate fraction of each cell that is covered is returned as well, for example to compute a weighted mean
exact: logical. If TRUE and y has polygons, the exact fraction of each cell that is covered is returned as well, for example to compute a weighted mean
touches: logical. If TRUE, values for all cells touched by lines or polygons are extracted, not just those on the line render path, or whose center point is within the polygon. Not relevant for points; and always considered TRUE when weights=TRUE or exact=TRUE
small: logical. If TRUE, values for all cells in touched polygons are extracted if none of the cells center points is within the polygon; even if touches=FALSE
weighted: logical. If TRUE, a weighted.mean is computed and fun is ignored. Weights are based on the length of the lines or the area of the polygons in x that intersect with z. This argument is ignored of x is a SpatVector or points
as.polygons: logical. Should the zonal statistics be combined with the geometry of z?
na.rm: logical. If TRUE, NAs are removed
Returns
A data.frame with a value for each zone, or a SpatRaster, or SpatVector of polygons.
See Also
See global for "global" statistics (i.e., all of x is considered a single zone), app for local statistics, and extract for an alternative way to summarize values of a SpatRaster with a SpatVector. With aggregate you can compute statistics for cell blocks defined by a number of rows and columns.