| tile_apply | R Documentation |
The function splits a SpatRaster into virtual tiles and applies a user supplied function to each tile, and assembles the per-tile results back into a single SpatRaster. The work can be distributed over a cluster of worker processes.
tile_apply(x, fun, cores=1, cpkgs=NULL, tiles=NULL, buffer=0, ...,
filename="", overwrite=FALSE, wopt=list(), overlap_fun=NULL)
x |
|
fun |
function. Takes a |
cores |
one of: an integer ( |
cpkgs |
character. Names of packages that must be loaded on each worker before |
tiles |
specification of the tiles. If |
buffer |
integer. Number of additional rows and columns (one number, or two for separate row/column buffers) of |
... |
additional arguments passed to |
filename |
character. Output filename for the assembled result. When empty (the default) and |
overwrite |
logical. If |
wopt |
list. Writing options as in |
overlap_fun |
character or |
Buffered tiles for focal-style operations. When tiles = NULL and buffer > 0, each tile is read on an expanded extent of (buffer cells on each side, clamped to x's extent), fun is applied, and the result is cropped back to the un-buffered tile extent before it is written. This avoids the edge effects that operations like focal would otherwise produce at tile boundaries.
The per-tile files are then assembled into the final SpatRaster:
When overlap_fun = NULL (the default), the assembly is a virtual raster (vrt). This is fast and correct as long as the tiles do not overlap. If they do, the value of the last tile in the overlapping regions is used.
When overlap_fun is set (e.g. "mean"), the assembly uses mosaic and applies the function to the values of overlapping cells.
If filename is empty and a VRT is returned, the tiled data files are kept for the rest of the R session, but they are lost after the session.
Extra arguments passed via ... must be named when cores > 1.
A SpatRaster.
getTileExtents, makeTiles, mosaic, vrt, window, wrap
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
# not parallel
# Returned object is a VRT backed by per-tile files in tempdir().
out1 <- tile_apply(r, function(x) x * 2)
# focal, use a buffer wide enough for the focal window
out3 <- tile_apply(r, function(x) focal(x, w=5, fun="mean",
na.rm=TRUE), buffer=2)
# parallel on 2 workers
## Not run:
out4 <- tile_apply(r, function(x) x * 2, cores=2)
# pass extra arguments by name; nested terra objects are auto-wrapped
out5 <- tile_apply(r, function(x, k) x * k, cores=2, tiles=50, k=10)
# use a future plan instead of a cluster
if (requireNamespace("future", quietly=TRUE) &&
requireNamespace("future.apply", quietly=TRUE)) {
future::plan(future::multisession, workers=2)
out6 <- tile_apply(r, function(x) x * 2, cores="future")
future::plan(future::sequential)
}
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.