I have a vector that looks like this:
mass<-c(-2, -6, -79, 31, -28, 198, 132, 0, 262, -187, -475, 701, 926)
I need to sum the following subset of values from this vector:
- all positive values;
- negative values if they are preceded in the vector by positive value.
So in the example vector above, I would like to exclude -2, -6, and -79 from the sum (they do not follow positive values), but include -28, -187, and -475 (since they are preceded in the vector by positive values).
I can sum. positive values with
sum(mass[mass>0])
But I’m not sure how to include only those negative values that meet my criteria.
(I have a large number of vectors I need to perform a similar operation for, and they do not all have the same sequence of negative/positive values, so I also can’t just deal with this problem by subsetting the vector to exclude the first three values, since the number of values to be excluded will differ depending on the vector).
Thank you very much for any help!
Note: This could fail if there are no positive values in the vector.