简体   繁体   中英

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

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

We can use rle in base R to create the group for ave by rep licating 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM