Example data
library(terra)
v <- c(1, 2, -40, 35, 10, 10)
cumsum(v)
#[1] 1 3 -37 -2 8 18
r <- rast(ncol=1, nrow=1, nlyr=6, vals=v)
If you want to set the negative values to zero, you can do that like this
x <- cumsum(r)
x <- ifel(x < 0, 0, x)
x
#class : SpatRaster
#dimensions : 1, 1, 6 (nrow, ncol, nlyr)
#resolution : 360, 180 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84
#source(s) : memory
#names : lyr.1, lyr.2, lyr.3, lyr.4, lyr.5, lyr.6
#min values : 1, 3, 0, 0, 8, 18
#max values : 1, 3, 0, 0, 8, 18
But that does not reset the cumulation at zero. If that is what you want you need something more complex. Perhaps like this:
cumsumreset <- function(x) {
if (x[1] < 0) x[1] <- 0
while(TRUE) {
v <- cumsum(x)
i <- which(v < 0)
if (length(i) == 0) break
i <- i[1]
x[i] <- x[i] - v[i]
}
v
}
cumsumreset(v)
#[1] 1 3 0 35 45 55
a <- app(r, cumsumreset)
a
#class : SpatRaster
#dimensions : 1, 1, 6 (nrow, ncol, nlyr)
#resolution : 360, 180 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84
#source(s) : memory
#names : lyr.1, lyr.2, lyr.3, lyr.4, lyr.5, lyr.6
#min values : 1, 3, 0, 35, 45, 55
#max values : 1, 3, 0, 35, 45, 55