I am quite new to R and tried some formulas form the forum but somehow I could not modify them to meet my condition. I want to construct a cumsum which starts new when the variable in column E is >=0:
NR E Proability Cumsum
1 -.2 .2 .2
2 -.15 .2 .4
3 -.1 .2 .6
4 .1 .2 .2
5 .2 .2 .4
The last column should be the result.
Does anyone have an idea?
Thank you very much :)
There's a very useful function called rleid
in the data.table
package which you can make use of for the grouping. I'll use it in combination with some base functions:
library(data.table)
df <- transform(df, cumsum2 = ave(Proability, rleid(E > 0), FUN = cumsum))
Or, if you want to fully use data.table functions, it would be
setDT(df)
df[, cumsum2 := cumsum(Proability), by = rleid(E > 0)]
setDF(df) # optional
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.