Search code examples
rr-rasterrolling-computationterra

R terra: rolling sum across layers


Having a large stack of timeserie rasters I would like to create another rasterstack which represents 5-day rolling sum per each pixel across the layers. Given the size of the raster stack, the raster::calc runs endlessly for this task, and I was therefore wondering if this operation could be implemented faster using the terra::lapp. However:

library(terra)
stack_A<-rast(nlyrs=10)
rollsum<-function(x){data.table::frollsum(x,n=5)}

stack_B<-lapp(stack_A, fun=rollsum)

returns an error:

"Error in (function (x)  : 
  unused arguments (c(0, 0,...

or: [lapp] I do not like 'fun' :("

Id be gratefull if somebody could suggest where the mistake is, or maybe suggest another implementation (stars::?)


Solution

  • You can use terra::app for that; terra::app is equivalent to raster::calc. You tried terra::lapp, that method is equivalent to raster::overlay.

    library(terra)
    library(data.table)
    f <- system.file("ex/logo.tif", package="terra")
    r <- rast(c(f,f,f,f))
    rollsum <- function(x){data.table::frollsum(x,n=5)} 
    
    x <- app(r, rollsum)
    

    I am not sure if this will be much faster, as the bottleneck probably is the rollsum function.

    "terra" has a function roll for this and I expect that to be much faster.

    library(terra)
    #terra 1.6.47
    f <- system.file("ex/logo.tif", package="terra")
    r <- rast(c(f,f,f,f))
    y <- roll(r, 5, "sum", type="to")