Learn R Programming

terra (version 0.8-5)

app: Apply a function to the cells of a SpatRaster

Description

Apply a function to values of each cell of a SpatRaster. This is similar to apply -- think of each layer in a SpatRaster as a column (or row) in a matrix.

You can also use a SpatDataSet to apply fun across datasets by layer.

Usage

# S4 method for SpatRaster
app(x, fun, ..., nodes=1, filename="", overwrite=FALSE, wopt=list())

# S4 method for SpatDataSet app(x, fun, ..., nodes=1, filename="", overwrite=FALSE, wopt=list())

Arguments

x

SpatRaster or SpatDataSet

fun

function

...

additional arguments for fun

nodes

positive integer. If nodes > 1, a 'parallel' package cluster with that many nodes is created. Ignored for C++ level implemented functions "max", "min", "mean", "range", "prod", "sum", "any", and "all"

filename

character. Output filename. Optional

overwrite

logical. If TRUE, filename is overwritten

wopt

list. Options for writing files as in writeRaster

Value

SpatRaster

Details

To speed things up, parallelization is supported, but this is often not helpful, and it may actually be slower. There is only a speed gain if you have many cores (> 8) and/or a very complex (slow) function fun. If you write fun yourself, consider supplying a cppFunction made with the Rcpp package instead (or go have a cup of tea while the computer works for you).

See Also

lapp, tapp, math

Examples

Run this code
# NOT RUN {
r <- rast(ncols=10, nrows=10)
values(r) <- 1:ncell(r)
x <- c(r, sqrt(r), r-50)
s <- app(x, fun=sum)
s
# for a few generic functions like 
# "sum", "mean", and "max" you can also do
sum(x)


## use a SpatDataSet
sd <- sds(x, x*2, x/3)
a <- app(sd, max)
a
# same as 
max(x, x*2, x/3)
# }

Run the code above in your browser using DataLab