I want to reset cumsum
over a vector as it reaches certain value.
E.g. for the following vector:
v <- c(3, 5, 2, 5, 3, 4, 5, 3, 1, 4)
expected output is:
c(0, 0, 10, 0, 0, 22, 0, 30, 0, 0)
With reset <- 10
I can reduce the task to flagging the first values after the full integer:
res <- cumsum(v)
resd <- res/reset
resd
# [1] 0.3 0.8 1.0 1.5 1.8 2.2 2.7 3.0 3.1 3.5
Expected output is this:
c(F, F, T, F, F, T, F, T, F, F) # or
c(0, 0, 1.0, 0, 0, 2.2, 0, 3.0, 0, 0)
I need a fast way to calculate one of those.
my (improved) solution:
v <- c(3, 5, 2, 5, 3, 4, 5, 3, 1, 4)
res <- cumsum(v)
reset <- 10
resd <- res/reset
res[diff(c(0, floor(resd))) == 0] <- 0
print(res) #gives 0 0 10 0 0 22 0 30 0 0
edit: now the first element in v
can be larger than 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With