tapp {terra} | R Documentation |
Apply a function to subsets of layers of a SpatRaster (similar to tapply
and aggregate
). The layers are combined based on the index
.
The function used should return a single value, and the number of layers in the output SpatRaster equals the number of unique values in index
.
For example, if you have a SpatRaster with 6 layers, you can use index=c(1,1,1,2,2,2)
and fun=sum
. This will return a SpatRaster with two layers. The first layer is the sum of the first three layers in the input SpatRaster, and the second layer is the sum of the last three layers in the input SpatRaster. Indices are recycled such that index=c(1,2)
would also return a SpatRaster with two layers (one based on the odd layers (1,3,5), the other based on the even layers (2,4,6)).
See app
or Summary-methods
if you want to use a more efficient function that returns multiple layers based on all layers in the SpatRaster object.
## S4 method for signature 'SpatRaster'
tapp(x, index, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list())
x |
SpatRaster |
index |
factor or numeric (integer). Vector of length |
fun |
function to be applied. The following functions have been re-implemented in C++ for speed: "sum", "mean", "median", "modal", "which", "which.min", "which.max", "min", "max", "prod", "any", "all", "sd", "std", "first". To use the base-R function for say, "min", you could use something like |
... |
additional arguments passed to |
cores |
positive integer. If |
filename |
character. Output filename |
overwrite |
logical. If |
wopt |
list with named options for writing files as in |
SpatRaster
r <- rast(ncols=10, nrows=10)
values(r) <- 1:ncell(r)
s <- c(r, r, r, r, r, r)
s <- s * 1:6
b1 <- tapp(s, index=c(1,1,1,2,2,2), fun=sum)
b1
b2 <- tapp(s, c(1,2,3,1,2,3), fun=sum)
b2