loop through RasterBrick to calculate differences between sequential layers

r, r-raster

Solution

This should do it.

subset(r, 2:nlayers(r)) - subset(r, 1:(nlayers(r)-1))

Conveniently the usual Ops just work for raster objects, so we can simply build the right pair of objects with highlevel tools.

Other approaches might be necessary depending on the data values and volumes.

Problem

I have a large `RasterBrick` object containing a time series of raster layers representing biomass at each time interval (irregular). What I need is a time series of the differences in biomass between two consecutive time periods (`difference in biomass = current biomass layer - last weeks biomass layer`). My thoughts have been to use a loop or one of the apply functions to go through the the `RasterBrick` and for each `RasterLayer` apply the function of subtraction with the one earlier in the time series. The `RasterBrick` is ordered so the actual time stamps are not necessarily important. I have tried to find examples but have failed to make progress. Any pointers would be very appreciated. I'm providing a quick example of my situation in the following: ``` library(raster) ``` Random set of 10 raster layers, into RasterStack ``` r <- raster(ncol=10, nrow=10) ;b <- brick( sapply(1:10, function(i) setValues(r, rnorm(ncell(r), i, 3)))) ``` Now I need a `RasterBrick` containing 9 layers with the results for difference in biomass = current biomass layer - last weeks biomass layer.

Original source