Manfred
Manfred

Reputation: 147

Using the calculated result of previous cell in r

I would like to use the calculated result of previous cell to compute the value of the current cell for the same column grouped by customer. The code that I am running is provided below:

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

i would be grateful for some help. Essentially EAD[i] = EAD[i-1] * BRD where EAD for Record_count== 1 should be equal to Vol

Upvotes: 0

Views: 44

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73275

Base R

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

dplyr

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

Upvotes: 1

Related Questions