Newbie question. I have a dataset that I am using to calculate some accounting values. The dataset looks like this
ID Period Amount Interest O_Bal C_Bal
1 1 1234 0.07 1234 (1234+(1234*0.07)) = 1321
1 2 1244 0.07 1321 (1321-1234+(1321*0.07))
1 3 .....
2 1 ......
...
Please ignore the actual values in the table. What I have at the moment is the first row for each ID. I need to create a loop for each ID group so that from period 2 onwards, it calculates the closing balance as per the formula in the second row. Any ideas?
I have tried the following
fin_calc$C_Bal = fin_calc$O_Bal + (fin_calc$O_Bal*0.07)
if (fin_calc$Period==1) {
fin_calc$Cl_Bal = fin_calc$C_Bal
}
fin_c <- fin_calc %>%
group_by(ID) %>%
mutate(Cl_Bal = lag(Cl_Bal) - Amount_PA + (lag(Cl_Bal) - Amount_PA)*0.07)
What this is doing is its able to continue from period 1 to period 2 but then subsequent periods are calculated incorrectly
Data <- data.frame(
ID = 1,
Period = c(1,2,3),
Amount_PA = c(0,2946737,3035139),
O_Bal = c(30979981.5,0,0),
C_Bal = c(33148580.2,0,0),
Cl_Bal = c(33148580.2,32221382.2,-3345026.6)
)