Applying cumsum to binary vector

2019-03-03 22:17发布

问题:

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! :-)

回答1:

The trick is to use diff to mark the transitions:

cumsum(as.logical(a+c(0,abs(diff(a)))))
 [1]  1  2  2  2  3  4  5  6  7  7  8  9  9  9 10 11