将求和应用于二进制向量 [英] Applying cumsum to binary vector
本文介绍了将求和应用于二进制向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的二进制向量a
,我尝试使用R函数cumsum
将其转换为向量b
.但是,cumsum
并不完全返回向量b
.
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
.
这里是一个例子:
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
问题在于,只要向量a
中出现0,则前一个数字应增加1,但仅对第一个0增加.其余数字将被赋予相同的值.
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! :-)
推荐答案
诀窍是使用diff
标记过渡:
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
这篇关于将求和应用于二进制向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文