raster (version 2.1-41)

zonal: Zonal statistics

Description

Compute zonal statistics, that is summarized values of a Raster* object for each "zone" defined by a RasterLayer. If stat is a true function, zonal will fail (gracefully) for very large Raster objects, but it will in most cases work for functions that can be defined as by a character argument ('mean', 'sd', 'min', 'max', or 'sum'). The function used should accept a na.rm argument. For example, if using fun=length fails, but fun=function(x, ...){length(x)} works. the ... argument 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)}}

Usage

## S3 method for class 'RasterLayer,RasterLayer':
zonal(x, z, fun='mean', digits=0, na.rm=TRUE, ...) 

## S3 method for class 'RasterStackBrick,RasterLayer':
zonal(x, z, fun='mean', digits=0, na.rm=TRUE, ...)

Arguments

x
Raster* object
z
RasterLayer with codes representing zones
fun
function to be applied to summarize the values by zone. Either as character: 'mean', 'sd', 'min', 'max', 'sum'; or, for relatively small Raster* objects, a proper function
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
...
additional arguments. One implemented: progress, as in writeRaster

Value

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

See Also

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

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)
# for big files, use a character value rather than a function
zonal(r, z, 'sum')

# for smaller files you can also provide a function
zonal(r, z, mean)
zonal(r, z, min)

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

Run the code above in your browser using DataLab