Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of positive entries until a negative occurs in R

Tags:

r

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?

like image 495
Harry McLellan Avatar asked Jan 30 '23 02:01

Harry McLellan


1 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 
like image 174
d.b Avatar answered Jan 31 '23 15:01

d.b