I have a stack with large number of layers, and I want to run a pixel-wise cumulative sum function across the layers with reset when sum becomes <0. Ive compiled the following code:
# given that "A" is an input stack with lengthy number of layers
B<-A
for(i in 2:nlyr(B)){
B[[i]]<-ifel((A[[i]]+B[[i-1]])>0, A[i]]+B[[i-1]], 0 )
}
, which works well but I have a large stack of rasters (in terms of nlyrs). Im wondering if there is a faster way to implement this task.
UPDATED. Apparently the function I posted before was incorrect. Below is a solution which benefits from parallelization of the operation via cores
argument in the terra::app
function. Though I assume this is not the most optimal suggestion.
library(terra)
v <- c(1, 2, -40, 35, 10, 10)
r <- rast(ncol=1, nrow=1, nlyr=6, vals=v)
r
cumsumreset <- function(x) {
for (i in 2:length(x)) {
if (x[i-1] < 0) x[i-1] <- 0
x[i] <- x[i] + x[i-1]
if (x[i] < 0) x[i] <- 0
}
x
}
a <- app(r, cumsumreset, cores=5)
a
P.S. My appologies and thanks to @RobertHijmans