R Cumulative Sum with a condition and a reset

后端 未结 3 557
日久生厌
日久生厌 2020-12-17 04:48

I have a signal position indicator vector consisting out of -1s and 1s. In addition, I have volume data which I want to sum based on the value of Signal. The basic data tabl

3条回答
  •  囚心锁ツ
    2020-12-17 05:29

    As suggested by @docendo this should work:

    df[,cum := cumsum(Volume)*Signal,.(rleid(Signal))]
    
              date Signal    Volume        cum
     1: 2016-01-04     NA  37912403         NA
     2: 2016-01-05     -1  23258238  -23258238
     3: 2016-01-06     -1  25096183  -48354421
     4: 2016-01-07     -1  45172906  -93527327
     5: 2016-01-08     -1  35402298 -128929625
     6: 2016-01-11     -1  29932385 -158862010
     7: 2016-01-12     -1  28395390 -187257400
     8: 2016-01-13     -1  33410553 -220667953
     9: 2016-01-14     -1  48658623 -269326576
    10: 2016-01-15      1  46132781   46132781
    11: 2016-01-19      1  30998256   77131037
    

提交回复
热议问题