Learn R Programming

terra (version 0.2-9)

rastApply: Apply a function to subsets of layers of a SpatRaster

Description

Apply a function to subsets of layers of a SpatRaster (similar to tapply and link[stats]{aggregate}). The layers are combined are combind based on the indices.

The function used should return a single value, and the number of layers in the output SpatRaster equals the number of unique values in indices.

For example, if you have a SpatRaster with 6 layers, you can use indices=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 indices=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 reduce or Summary-methods if you want to use a more efficient function that returns multiple layers based on all layers in the SpatRaster object.

Usage

# S4 method for SpatRaster
rastApply(x, indices, fun, ..., filename="", overwrite=FALSE, wopt=list())

Arguments

x

SpatRaster

indices

integer. Vector of length nlayers(x) (shorter vectors are recycled) grouping the input layers

fun

function to be applied

...

additional arguments passed to fun

filename

character. Output filename. Optional

overwrite

logical. If TRUE, filename is overwritten

wopt

list. Options for writing files as in writeRaster

Value

SpatRaster

See Also

reduce, Summary-methods, rastSelect

Examples

Run this code
# NOT RUN {
r <- rast(ncol=10, nrow=10)
values(r) <- 1:ncell(r)
s <- c(r, r, r, r, r, r)
s <- s * 1:6
b1 <- rastApply(s, indices=c(1,1,1,2,2,2), fun=sum)
b1
b2 <- rastApply(s, indices=c(1,2,3,1,2,3), fun=sum)
b2
# }

Run the code above in your browser using DataLab