I need to model a basic balance sheet, in which 1) final balance is initial balance plus cash flow, and 2) initial balance is equal to previous final balance. The following code works fine:
init_balance <- c(0,0,0,0)
cash_flow <- 1:4
final_balance <- c(0,0,0,0)
n <- length (final_balance)
for (i in 1:n) {
final_balance[i] <- init_balance[i] + cash_flow[i]
if(i < n) {
init_balance[i+1] <- final_balance[i]
}
}
> init_balance
[1] 0 1 3 6
> cash_flow
[1] 1 2 3 4
> final_balance
[1] 1 3 6 10
However, this implementation uses for
loops and does not sound R-ish to me. All financial packages I have found are related to financial analysis, not financial modelling.
Would someone suggest another approach or package for this kind of modelling?
Thank you.
A base R-ish way could look like this.
finance <- data.frame(cash.flow=1:4)
within(finance, {
final.balance <- cumsum(cash.flow)
init.balance <- final.balance - cash.flow
})
# cash.flow init.balance final.balance
# 1 1 0 1
# 2 2 1 3
# 3 3 3 6
# 4 4 6 10
The difference is that this solution (and that of the other answer) calculates with the whole vector at the same time and not with every single value, which could be termed "R-ish".