You can use Reduce in that we add the numbers but if the next number is zero, we start adding again. It is tweaking the cumsum function with an ifelse. ie. Reduce(function(a,b),a+b,x,,T) is the cumsum(x) function.Now we just introduce an ifelse statement so that every moment the next value is zero, set the sum to zero and start adding again. Here is the code:
Reduce(function(a,b)ifelse(b==0,0,a)+b,x,accumulate = T)
[1] 0 0 1 2 3 0 1 0 1 2 0
you can also use <<- and implement same logic as above
c(b<-0,sapply(x,function(a)b<<-ifelse(a==0,b<-0,a)+b))[-1]#Remove the first b<-0 that I added
[1] 0 0 1 2 3 0 1 0 1 2 0
in the first one, the cumulative sum is taken to be a, while in the second one the cumulative sum is taken to be b