I have for example the following dataframe :
p1 <- data.frame(x = c(1:3), y=c(2,1,0), z=c(1,0,0))
For each row, I want to create a new data set (p2) which appears to be the accumulated values of p1, and the cumulative value should become 0 if the added value equals 0.
The result should be:
p2 <- data.frame(x = c(1:3), y=c(3,3,0), z=c(4,0,0))
I had a million rows to deal with, do you have any idea on how to do this?
CodePudding user response:
From the comments, it sounds as though once a zero occurs in a row, the rest of the row should remain 0. That being the case, we could do:
as.data.frame(t(apply(p1, 1, function(x) cumsum(x) * cumprod(sign(x)))))
#> x y z
#> 1 1 3 4
#> 2 2 3 0
#> 3 3 0 0
Created on 2022-11-24 with reprex v2.0.2