Sum of positive entries until a negative value occurs in R

As an example, I have a vector of 20 mixed positive and negative integers. I would like to generate a new vector where each positive integer is added together to negative integers, and then each negative integer is added until a positive result occurs.

eg. 2 4 3 -4 -4 -3 -2 3 4 5 2 5 -4 -4 -3 -3 3 4 5will become 9 -13 19 -14 12.

What code should I use? Is it possible?

+4
source share
2 answers
#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 
+6
source

You can also use tapplya group constructed from diff, abs, signand cumsum.

Using db data, the result

unname(tapply(x, cumsum(c(0, abs(diff(sign(x))))), sum))
 [1]  24 -17   6 -35  29 -10   4 -17  14 -19  15  -9
Sign

-1, 1 0 . diff , , abs diff , , cumsum tapply.

+2

Source: https://habr.com/ru/post/1690236/


All Articles