Learn R Programming

raster (version 1.8-3)

zonal: Zonal statistics

Description

Compute zonal statistics. That is, cross-tabulate the values of a Raster* object based on a "zones" RasterLayer. NA values are removed.

Usage

zonal(x, zones, stat='mean', digits=0, na.rm=TRUE, progress)

Arguments

x
Raster* object
zones
RasterLayer object with codes representing zones
stat
The function to be applied. Either as character: 'mean', 'min', 'max', 'sum'; or a function (see Details)
digits
Integer. Number of digits to maintain in 'zones'. By default averaged to an integer (zero digits)
na.rm
Logical. If TRUE, NA values in x are ignored
progress
Character. "text", "window", or "" (the default, no progress bar)

Value

  • A matrix with a value for each zone (unique value in zones)

Details

If stat is a function, zonal will fail (gracefully) for very large RasterLayers. The function should accept a na.rm argument. For example, fun=length will fail, but fun(x, ...)=length(x) will work (the '...' arguments catches the na.rm argument, but it is ignored in this case).

Examples

Run this code
r <- raster(ncols=10, nrows=10)
r[] <- runif(ncell(r)) * 1:ncell(r)
z <- r
z[] <- rep(1:5, each=20)
zonal(r, z, mean)
zonal(r, z, min)
# for big files, use a character value rather than a function
zonal(r, z, 'sum')

# multiple layers
zonal(stack(r, r*10), z, 'sum')

Run the code above in your browser using DataLab