I have a simple binary vector a
which I try to translate into vector b
using the R function cumsum
. However, cumsum
does not exactly return vector b
.
Here is an example:
a <- c(1,0,0,0,1,1,1,1,0,0,1,0,0,0,1,1)
b <- c(1,2,2,2,3,4,5,6,7,7,8,9,9,9,10,11)
> cumsum(a)
[1] 1 1 1 1 2 3 4 5 5 5 6 6 6 6 7 8
The problem is that whenever a 0 appears in vector a
then the previous number should be increased by 1 but only for the first 0. The remaining ones are given the same value.
Any advise would be great! :-)