Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset cumsum as it reaches certain value

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.

like image 792
Bulat Avatar asked Dec 04 '22 00:12

Bulat


1 Answers

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.

like image 92
Qaswed Avatar answered Dec 06 '22 13:12

Qaswed