Albert
Albert

Reputation: 197

Pick up numbers from a series every time a positive appears

I would like to create a new series of numbers picking up numbers every time a positive one appears and leaving numbers every time a negative one appears. For example :

f <- c(1,34,56,-3,-26,-4,-1,17,28,-6,-9,-3,12,-13,15,18)

Into:

g = 34  56  -3 28  -6  -13  18

#[+1](positive:start) 34  56  -3 (negative:stop) 
#[-26,-4,-1, +17](positive:start) 28 -6 (negative:stop)etc...

I hope to be clear.

I would like also to do another different thing: every time i find a negative number the next numbers will become negative until a positive appear. For example:

From

f <- c(1,34,56,-3,-26,-4,-1,17,28,-6,-9,-3,12,-13,15,18)

Into

h = 34  56  -3 (negative: change sign)  26  4  1  -17(was positive: back to normal sign) 28 -6  etc...

Any help?

Upvotes: 1

Views: 56

Answers (1)

akuiper
akuiper

Reputation: 214957

library(dplyr)
f[lag(f > 0)][-1]
[1]  34  56  -3  28  -6 -13  18

Upvotes: 7

Related Questions