A fast data.table-based alternative to
raster::zonal().
Arguments
- x
A
Raster*to the totality of whose valuesfunshould be applied within each zone.- z
A categorical
RasterLayerwith 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
xmight contain anyNAvalues, it should be equipped to handle them. For large rasters, this function needs to be one, likesum()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,NAvalues inxare ignored.
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