As an example I have a vector of 20 mixed positive and negative integers. I would like a generate a new vector where every positive integer is added together until a negative integers occurs and then every negative is added until a positive occurs again.
e.g. 2 4 3 -4 -4 -3 -2 3 4 5 2 5 -4 -4 -3 -3 3 4 5  would become 9 -13 19 -14 12.
What sort of code should I use? Is this even possible?
#DATA
set.seed(1)
x = sample(c(1, -1), 20, TRUE) * sample(1:20, 20, TRUE)
x
# [1]  19   5 -14  -3   6  -8  -1  -8 -18   7  10  12 -10   4 -17  14 -16  -3  15  -9
sapply(split(x, with(rle(x > 0), rep(1:length(values), lengths))), sum)
#  1   2   3   4   5   6   7   8   9  10  11  12 
# 24 -17   6 -35  29 -10   4 -17  14 -19  15  -9 
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