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

stackApply

Apply a function on subsets of a RasterStack or RasterBrick


Description

Apply a function on subsets of a RasterStack or RasterBrick. The layers to be combined are indicated with the vector indices. The function used should return a single value, and the number of layers in the output Raster* equals the number of unique values in indices. For example, if you have a RasterStack with 6 layers, you can use indices=c(1,1,1,2,2,2) and fun=sum. This will return a RasterBrick with two layers. The first layer is the sum of the first three layers in the input RasterStack, and the second layer is the sum of the last three layers in the input RasterStack. Indices are recycled such that indices=c(1,2) would also return a RasterBrick with two layers (one based on the odd layers (1,3,5), the other based on the even layers (2,4,6)).

See calc if you want to use a more efficient function that returns multiple layers based on _all_ layers in the Raster* object.

Usage

stackApply(x, indices, fun, filename='', na.rm=TRUE, ...)

Arguments

x

Raster* object

indices

integer. Vector of length nlayers(x) (shorter vectors are recycled) containing all integer values between 1 and the number of layers of the output Raster*

fun

function that returns a single value, e.g. mean or min, and that takes a na.rm argument (or can pass through arguments via ...)

na.rm

logical. If TRUE, NA cells are removed from calculations

filename

character. Optional output filename

...

additional arguments as for writeRaster

Value

A new Raster* object, and in some cases the side effect of a new file on disk.

See Also

Examples

r <- raster(ncol=10, nrow=10)
values(r) <- 1:ncell(r)
s <- brick(r,r,r,r,r,r)
s <- s * 1:6
b1 <- stackApply(s, indices=c(1,1,1,2,2,2), fun=sum)
b1
b2 <- stackApply(s, indices=c(1,2,3,1,2,3), fun=sum)
b2

raster

Geographic Data Analysis and Modeling

v3.4-10
GPL (>= 3)
Authors
Robert J. Hijmans [cre, aut] (<https://orcid.org/0000-0001-5872-2872>), Jacob van Etten [ctb], Michael Sumner [ctb], Joe Cheng [ctb], Dan Baston [ctb], Andrew Bevan [ctb], Roger Bivand [ctb], Lorenzo Busetto [ctb], Mort Canty [ctb], Ben Fasoli [ctb], David Forrest [ctb], Aniruddha Ghosh [ctb], Duncan Golicher [ctb], Josh Gray [ctb], Jonathan A. Greenberg [ctb], Paul Hiemstra [ctb], Kassel Hingee [ctb], Institute for Mathematics Applied Geosciences [cph], Charles Karney [ctb], Matteo Mattiuzzi [ctb], Steven Mosher [ctb], Babak Naimi [ctb], Jakub Nowosad [ctb], Edzer Pebesma [ctb], Oscar Perpinan Lamigueiro [ctb], Etienne B. Racine [ctb], Barry Rowlingson [ctb], Ashton Shortridge [ctb], Bill Venables [ctb], Rafael Wueest [ctb]
Initial release
2021-05-02

We don't support your browser anymore

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