Applying cumsum to binary vector

懵懂的女人 提交于 2019-12-20 07:15:16

问题


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


来源:https://stackoverflow.com/questions/11537041/applying-cumsum-to-binary-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!