The approach that comes to mind is to find the runs (rle()
) defined by the
condition (sign()
) in the data, apply cumsum()
on each run separately
(tapply()
), and the concatenate back into a vector (unlist()
). Something
like this:
vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)
run_length <- rle(sign(vector_A))$lengths
run_id <- rep(seq_along(run_length), run_length)
unlist(tapply(vector_A, run_id, cumsum), use.names = FALSE)
#> [1] 1 2 -1 -2 -3 1 -1 -2 1 -1
Wrapping the process up a bit, I’d maybe put finding the grouping factor (run
index) in a function? And then the grouped summary will need to be done using
existing tools, like tapply()
above, or a creative ave()
, or in the
context of data frames, a group_by()
and summarise()
with dplyr.
run_index <- function(x) {
with(rle(x), rep(seq_along(lengths), lengths))
}
ave(vector_A, run_index(sign(vector_A)), FUN = cumsum)
#> [1] 1 2 -1 -2 -3 1 -1 -2 1 -1