I want to do a cumulative sum with an lower and upper bound so that the summation never goes below a lower or above an upper bound. However, the upper boundary should be a variable value given as a vector to the function, and should not be a fixed value as in this post text.
I tried to use the cumsum.bounded function proposed by @G. Grothendieck of the above mentioned function, however it only takes one upper bound.
Here is some example data:
test_data <- tibble(prec_et = c(1,2,-1,-3,5,4,5,4,3,-3,-2,4,3,4),
upper_bound = c(10,10,10,10,10,10,10,13,14,15,16,17,18,19,20))
and my expected output of the function should be like # [1] 1 3 2 0 4 9 13 14 15 12 10 14 18 20
or here the same as snip of an excel table:
excel-table-snip
Thanks for any help on this topic!
3
test_data$cs <- cumsum(test_data$prec_et)
test_data$cs_bounded <- with(test_data, pmax(0, pmin(upper_bound, cumsum(prec_et))))
test_data
# prec_et upper_bound cs cs_bounded
# 1 1 10 1 1
# 2 2 10 3 3
# 3 -1 10 2 2
# 4 -3 10 -1 0
# 5 5 10 4 4
# 6 4 10 8 8
# 7 5 10 13 10
# 8 4 13 17 13
# 9 3 14 20 14
# 10 -3 15 17 15
# 11 -2 16 15 15
# 12 4 17 19 17
# 13 3 18 22 18
# 14 4 19 26 19
Where
test_data <- data.frame(
prec_et = c(1, 2, -1, -3, 5, 4, 5, 4, 3, -3, -2, 4, 3, 4),
upper_bound = c(10, 10, 10, 10, 10, 10, 10, 13, 14, 15, 16, 17, 18, 19)
)