How to find conditional sum in R based on positive and negative values

Viewed 115

This question might be a duplicate but still asking!

I have this list where i need to do a conditional sum over the positve and negative values. i could do this with data table using this. But im looking for a base R solution.

list1 = list(
    x=c(1,1,-1,-1,1),
    y=c(-1,-1,1,-1,-1)
    )

lapply(list1, function(x) ave(x, rleid(x), FUN = cumsum))

$x
[1]  1  2 -1 -2  1

$y
[1] -1 -2  1 -1 -2
1 Answers

We can use rle in base R to create the group for ave by replicating the sequence of 'values' with the lengths created with rle

lapply(list1, function(x) ave(x, with(rle(x),
         rep(seq_along(values), lengths)), FUN = cumsum))
#$x
#[1]  1  2 -1 -2  1

#$y
#[1] -1 -2  1 -1 -2

Or another option is to check the difference of adjacent elements (for numeric), then do the cumulative sum to create the group

lapply(list1, function(x) ave(x,  cumsum(c(TRUE, diff(x) != 0)) , FUN = cumsum))

Or for a general case, just remove the first and last elements, do a comparison to create the group

lapply(list1, function(x) ave(x, cumsum(c(TRUE, head(x, -1)
             != tail(x, -1))), FUN = cumsum))
Related