简体   繁体   English

R中的资产负债表建模

[英]Balance sheet modeling in R

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.我需要对基本资产负债表进行建模,其中 1) 最终余额是初始余额加上现金流量,2) 初始余额等于之前的最终余额。 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.但是,这个实现使用for循环,对我来说听起来并不 R-ish。 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.谢谢你。

No need for loops and all you really need is cash_flow to start:不需要循环,你真正需要的是cash_flow开始:

library(tidyverse)

df <- tibble(
  cash_flow = 1:4
)
df
#> # A tibble: 4 x 1
#>   cash_flow
#>       <int>
#> 1         1
#> 2         2
#> 3         3
#> 4         4

df %>%
  mutate(
    final_balance = cumsum(cash_flow),
    init_balance = lag(final_balance, 1, default = 0)
  )
#> # A tibble: 4 x 3
#>   cash_flow final_balance init_balance
#>       <int>         <int>        <dbl>
#> 1         1             1            0
#> 2         2             3            1
#> 3         3             6            3
#> 4         4            10            6

Created on 2019-03-21 by the reprex package (v0.2.1)reprex 包(v0.2.1) 于 2019 年 3 月 21 日创建

Your final_balance is just the cumulative cash flows.您的final_balance只是累积现金流量。 For init_balance we are using lag of the final_balance by 1 period (think 1 period prior);对于init_balance我们使用的是final_balancelag 1 个周期(想想 1 个周期之前); we are also setting its default amount to zero instead of NA .我们还将其默认数量设置为零而不是NA

A base R-ish way could look like this.一个基本的 R-ish 方式可能是这样的。

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".不同之处在于该解决方案(以及其他答案的解决方案)同时计算整个向量,而不是每个值,这可以称为“R-ish”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM