Compute zonal statistics, that is summarize values of a SpatRaster for each "zone" defined by another SpatRaster.
If fun
is a true R function
, zonal
may fail for very large SpatRaster objects, 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.
See extract
to summarize values of a SpatRaster with a SpatVector.
# S4 method for SpatRaster,SpatRaster
zonal(x, z, fun=mean, ..., as.raster=FALSE, filename="", wopt=list()) # S4 method for SpatVector,SpatVector
zonal(x, z, fun=mean, ..., weighted=FALSE, as.polygons=FALSE)
A data.frame
with a value for each zone) or a SpatRaster or SpatVector of polygons
SpatRaster or SpatVector
Object of the same class as x
. That is, either a SpatRaster with cell-values representing zones or a SpatVector with each polygon geometry representing a zone
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
logical. If TRUE
, a SpatRaster is returned with the zonal statistic for each zone
character. Output filename (ignored if as.raster=FALSE
list with additional arguments for writing files as in writeRaster
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
logical. Should the results be merged with the attributes of z
?
See global
for "global" statistics (i.e., all of x
is considered a single zone), app
for local statistics, and extract
for summarizing values for polygons
r <- rast(ncols=10, nrows=10)
values(r) <- 1:ncell(r)
z <- rast(r)
values(z) <- rep(c(1:2, NA, 3:4), each=20)
names(z) <- "zone"
zonal(r, z, "sum", na.rm=TRUE)
# multiple layers
r <- rast(system.file("ex/logo.tif", package = "terra"))
# zonal layer
z <- rast(r, 1)
names(z) <- "zone"
values(z) <- rep(c(1:2, NA, c(3:4)), each=ncell(r)/5, length.out=ncell(r))
zonal(r, z, "mean", na.rm = TRUE)
# raster of zonal values
zr <- zonal(r, z, "mean", na.rm = TRUE, as.raster=TRUE)
### SpatVector
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)[,c(2,4)]
p <- spatSample(v, 100)
values(p) <- data.frame(b2=1:100, ssep1=100:1)
zonal(p, v, mean)
Run the code above in your browser using DataLab