Learn R Programming

raster (version 1.9-44)

zonal: Zonal statistics

Description

Compute zonal statistics, values of a Raster* object for each "zone" in a RasterLayer.

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=function(x, ...){length(x)} will work; the '...' arguments catches the na.rm argument, even though it is not used by the function in this case. To remove NA values, you could use this function: fun=function(x, na.rm){ if(na.rm){length(na.omit(x))}else{length(x)}}

See Also

See cellStats for 'global' statistics (i.e., all of x is considered a single zone)

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