Skip to contents

A fast data.table-based alternative to raster::zonal().

Usage

zonalDT(x, z, fun = sum, na.rm = TRUE)

Arguments

x

A Raster* to the totality of whose values fun should be applied within each zone.

z

A categorical RasterLayer with codes representing zones.

fun

A name or character string giving the function to be applied to summarize the values by zone. It needs to return a single (or at least a length-one vector). If x might contain any NA values, it should be equipped to handle them. For large rasters, this function needs to be one, like sum() whose value is the same even if carried out in a two-stage application (i.e. first to data subsets and then to the results of those subset applications).

na.rm

Logical. If TRUE, NA values in x are ignored.

Value

A data.table with a summary value for each zone.

Author

Joshua O'Brien

Examples

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
zonalDT(r, z, "sum")
#>    z    layer
#> 1: 1 123.4224
#> 2: 2 298.8698
#> 3: 3 535.5253
#> 4: 4 730.3385
#> 5: 5 945.2900

## for smaller files you can also provide a function
zonalDT(r, z, mean)
#>    z     layer
#> 1: 1  6.171121
#> 2: 2 14.943491
#> 3: 3 26.776267
#> 4: 4 36.516924
#> 5: 5 47.264499
zonalDT(r, z, min)
#>    z     layer
#> 1: 1 0.3669905
#> 2: 2 1.6426280
#> 3: 3 0.3910445
#> 4: 4 1.5849348
#> 5: 5 3.3435498

## multiple layers
zonalDT(stack(r, r*10), z, "sum")
#>    z  layer.1  layer.2
#> 1: 1 123.4224 1234.224
#> 2: 2 298.8698 2988.698
#> 3: 3 535.5253 5355.253
#> 4: 4 730.3385 7303.385
#> 5: 5 945.2900 9452.900