Let's say I need to take cumulative sum of a vector
set.seed(123)
x <- sample(-5:5, 15,replace = T)
x
-2 3 -1 4 5 -5 0 4 1 0 5 -1 2 1 -4
x are values for 15 days with first value belonging to day 1
I can take cumsum of x as
cumsum(x)
-2 1 0 4 9 4 4 8 9 9 14 13 15 16 12
However, the condition I want to impose is that at any given day, cumsum cannot exceed 10 or go negative. If for a day, it exceeds 10, make it 10 or if it is less than zero, make it zero.
I did this:
ifelse(10 + cumsum(x) < 0, 0, ifelse(10 + cumsum(x) > 10, 10,cumsum(x)))
-2 10 0 10 10 10 10 10 10 10 10 10 10 10 10
This does not give me the right answer since my first value is negative and values which are less than 10 are converted into 10. What am I doing wrong?
EDIT
if this is x, -2,3,-1,4,5,-5,0,4,1,0,5,-1,2,1,-4
then the calculation is: 8 (10 - 2= 8)
10 (8 + 3 = 11, converted into 10)
9 (10 - 1 = 9)
10 (9 + 4 = 13, converted into 10)
10 (10 + 5 = 15, converted into 10)
5 (10 - 5 = 5)
5 (5 + 0 = 5)
9 (5 + 4 = 9)
10 (9 + 1 = 10)
10 (10 + 0 = 10)
10 (10 + 5 = 15, converted into 10)
9 (10 - 1 = 9)
10 (9 + 2 = 11, converted into 10)
10 (10 + 1 = 11, converted into 10)
6 (10 -4 = 6)
Final answer should be:
8, 10, 9, 10, 10, 5,5,9,10,10,10,9,10,10,6