Search code examples
rif-statementvectorconditional-statementscumsum

How to cumsum the elements of a vector under certain condition in R?


My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)

How can I achieve this?


Solution

  • A base R option with Reduce

    > Reduce(function(x, y) ifelse(x * y > 0, x + y, y), vector_A, accumulate = TRUE)
     [1]  1  2 -1 -2 -3  1 -1 -2  1 -1
    

    or using ave + cumsum

    > ave(vector_A, cumsum(c(1, diff(sign(vector_A)) != 0)), FUN = cumsum)
     [1]  1  2 -1 -2 -3  1 -1 -2  1 -1