2016-11-06 75 views
3

這是我的data.table貌似。最後一欄NewShares是我期望的專欄。R基於兩個變量的累積和

library(data.table) 
dt <- fread(' 
    Client Level NumShares Interest NewShares 
    A   0  10   0   10 
    A   0  0   0   10 
    A   1  0   .1   11 
    A   0  9   0   20 
    A   1  0   .2   24') 

我想累積NumShares,同時考慮NewShares買興趣。因此截至第一排,累計股數爲10.截至第三排,Level==1,所以我必須增加興趣。它將是10+(10*.1)=11。截至第四行,累計股份爲11+9 =20。隨着最後一排,Level==1的,所以新股20+(20*.2) = 24

我想:

dt[,NewShares:= NumShares* cumprod(1+ NumShares*Interest),by=Client] 
+0

也許'DT [,NewSharesN包裝它: =上限(cumsum(cumsum(NumShares)* Interest + NumShares)),客戶]' – akrun

回答

3

我們可以做雙cumsumceiling

dt[, NewSharesN := ceiling(cumsum(cumsum(NumShares)*Interest + NumShares)) , by = Client] 
dt 
# Client Level NumShares Interest NewShares NewSharesN 
#1:  A  0  10  0.0  10   10 
#2:  A  0   0  0.0  10   10 
#3:  A  1   0  0.1  11   11 
#4:  A  0   9  0.0  20   20 
#5:  A  1   0  0.2  24   24