Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

app

Apply a function to the cells of a SpatRaster


Description

Apply a function to values of each cell of a SpatRaster. Similar to apply – think of each layer in a SpatRaster as a column (or row) in a matrix. This is generally used to summarize the values of multiple layers into one layer; but this is not required.

You can also apply a function fun across datasets by layer of a SpatRasterDataset. In that case, summarization is across SpatRasters, not across layers.

Usage

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

## S4 method for signature 'SpatRasterDataset'
app(x, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list())

Arguments

x

SpatRaster or SpatRasterDataset

fun

function

...

additional arguments for fun

cores

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

filename

character. Output filename

overwrite

logical. If TRUE, filename is overwritten

wopt

list with named options for writing files as in writeRaster

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).

Value

SpatRaster

See Also

Examples

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)

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

## also works for a single layer
f <- function(i) (i+1) * 2 * i + sqrt(i)
s <- app(r, f)
# same as above, but that is not memory-safe
# and has no filename argument 
s <- f(r)

terra

Spatial Data Analysis

v1.2-10
GPL (>= 3)
Authors
Robert J. Hijmans [cre, aut] (<https://orcid.org/0000-0001-5872-2872>), Roger Bivand [ctb] (<https://orcid.org/0000-0003-2392-6140>), Karl Forner [ctb], Jeroen Ooms [ctb] (<https://orcid.org/0000-0002-4035-0289>), Edzer Pebesma [ctb] (<https://orcid.org/0000-0001-8049-7069>)
Initial release
2021-05-12

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.