You can calculate the run lengths of each sign using rle
from base
to and do something like this.
set.seed(0)z <- round(rnorm(20, sd = 0.02), 3)run_lengths <- rle(sign(z))$lengthsrun_lengths# [1] 1 1 1 3 1 1 2 2 1 2 2 1 1 1
To get n_of_sequence
n_of_sequence <- run_lengths %>% map(seq) %>% unlistn_of_sequence# [1] 1 1 1 1 2 3 1 1 1 2 1 2 1 1 2 1 2 1 1 1
Finally, to get the summations of the sequences,
start <- cumsum(c(1,run_lengths))start <- start[-length(start)] # start points of each series map2(start,run_lengths,~cumsum(z[.x:(.x+.y-1)])) %>% unlist()# [1] -0.010 0.003 -0.002 0.018 0.020 0.026 -0.012 0.014 -0.017 -0.024# [11] 0.002 0.004 -0.004 0.015 0.017 -0.001 -0.009 0.010 -0.018 0.046