I have this vector :
x = c(1,1,1,1,1,0,1,0,0,0,1,1)
And I want to do a cumulative sum for the positive numbers only. I should have the fol
One option is
x1 <- inverse.rle(within.list(rle(x), values[!!values] <- (cumsum(values))[!!values])) x[x1!=0] <- ave(x[x1!=0], x1[x1!=0], FUN=seq_along) x #[1] 1 2 3 4 5 0 1 0 0 0 1 2
Or a one-line code would be
x[x>0] <- with(rle(x), sequence(lengths[!!values])) x #[1] 1 2 3 4 5 0 1 0 0 0 1 2