### SpatRaster, SpatRaster
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)
# with weights
w <- init(r, "col")
zonal(r, z, w=w, "mean", 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)
### SpatRaster, SpatVector
x <- rast(ncol=2,nrow=2, vals=1:4, xmin=0, xmax=1, ymin=0, ymax=1, crs="+proj=utm +zone=1")
p <- as.polygons(x)
pp <- shift(p, .2)
r <- disagg(x, 4)
zonal(r, p)
zonal(r, p, sum)
zonal(x, pp, exact=TRUE)
zonal(c(x, x*10), pp, w=x)
### SpatVector, 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