Last chance! 50% off unlimited learning
Sale ends in
Apply a function to a cell-varying range of the layers of a SpatRaster. The range is specified for each cell separately by two other SpatRasters (arguments first
and last
. For either first
or last
you can use a constant instead.
If the specified range is outside 1:nlyr(x)
, NA
is returned. You could use clamp
to assure that this is the case.
See app
or Summary-methods
if you want to apply a function to all layers (perhaps after making a subset
) of a SpatRaster.
# S4 method for SpatRaster
rapp(x, first, last, fun, ..., allyrs=FALSE, fill=NA,
filename="", overwrite=FALSE, wopt=list())
SpatRaster
SpatRaster or positive integer between 1 and nlyr(x), indicating the first layer in the range of layers to be considered
SpatRaster or positive integer between 1 and nlyr(x), indicating the last layer in the range to be considered
function to be applied
additional arguments passed to fun
logical. Should the values of all layers be passed to fun
. The values outside of the range are set to fill
numeric. The fill value for the the values outside of the range, for when allyrs=TRUE
character. Output filename
logical. If TRUE
, filename
is overwritten
list with named options for writing files as in writeRaster
SpatRaster
# NOT RUN {
r <- rast(ncol=9, nrow=9)
values(r) <- 1:ncell(r)
s <- c(r, r, r, r, r, r)
s <- s * 1:6
s[1:2] <- NA
start <- end <- rast(r)
start[] <- 1:3
end[] <- 4:6
a <- rapp(s, start, end, fun="mean")
b <- rapp(s, start, 2, fun="mean")
# cumsum from start to nlyr(x). return all layers
r <- rapp(s, start, nlyr(s), cumsum, allyrs=TRUE, fill=0)
# return only the final value
rr <- rapp(s, start, nlyr(s), function(i) max(cumsum(i)))
# }
Run the code above in your browser using DataLab