使用r中上一个单元格的计算结果



我想使用上一个单元格的计算结果来计算按客户分组的同一列的当前单元格的值。我正在运行的代码如下所示:

df <- data.frame(Cust = c(1,1,1,2,2,2), Rec_count = c(1,2,3,1,2,3), BRD = c(1,0.9,0.9, 1, 0.8, 0.8), T_y = c(2,2,2,1,1,1), Vol = c(100,100,100,80,80,80))
### the Caclulated variabele is EAD which is BRD*lag(EAD)
### For Rec_count = 1, EAD = Vol
df <- df %>% mutate(
EAD = ifelse(Rec_count==1, Vol, NA)
)
### then I run this code 
df1 <- df %>% group_by (Cust) %>%
mutate(EAD = accumulate(BRD[1:n()], function(x, y) x * y))
### The answer in the EAD column should be 100, 90, 81 and 80, 64, 51.2 ####
Cust  Rec_count   BRD   T_y   Vol   EAD
<dbl>     <dbl> <dbl> <dbl> <dbl>  <dbl>
1     1         1   1       2   100  1   
2     1         2   0.9     2   100  0.9 
3     1         3   0.9     2   100  0.81
4     2         1   1       1    80  1   
5     2         2   0.8     1    80  0.8 
6     2         3   0.8     1    80  0.64

如果能给我一些帮助,我将不胜感激。本质上EAD[i]=EAD[i-1]*BRD,其中Record_count==1的EAD应等于Vol

基本R

df$EAD <- with(df, ave(BRD, Cust, FUN = cumprod) * Vol)

dplyr

df %>% group_by(Cust) %>% mutate(EAD = Vol * cumprod(BRD))

最新更新