In R, you can use data.table
s rleid
to create groups with positive and negative series of number and then create a sequence of rows in each group and do a cumulative sum of the x
values.
library(data.table)df <- data.table(x)df[, c("n_of_sequence", "sum") := list(seq_len(.N), cumsum(x)), by = rleid(sign(x))]df# x n_of_sequence sum# 1: -0.010 1 -0.010# 2: 0.003 1 0.003# 3: -0.002 1 -0.002# 4: 0.018 1 0.018# 5: 0.002 2 0.020# 6: 0.006 3 0.026# 7: -0.012 1 -0.012# 8: 0.014 1 0.014# 9: -0.017 1 -0.017#10: -0.007 2 -0.024#11: 0.002 1 0.002#12: 0.002 2 0.004#13: -0.004 1 -0.004#14: 0.015 1 0.015#15: 0.002 2 0.017#16: -0.001 1 -0.001#17: -0.008 2 -0.009#18: 0.010 1 0.010#19: -0.018 1 -0.018#20: 0.046 1 0.046
We can use rleid
in dplyr
as well to create groups and do the same.
library(dplyr)df %>% group_by(gr = data.table::rleid(sign(x))) %>% mutate(n_of_sequence = row_number(), sum = cumsum(x))