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
coresargument in theterra::appfunction. Though I assume this is not the most optimal suggestion.P.S. My appologies and thanks to @RobertHijmans