【发布时间】:2021-05-12 05:52:33
【问题描述】:
下面的答案非常有帮助。但我过度简化了我原来的问题。我想如果我过度简化然后适应我的实际需要,我会学到更多,但现在我被困住了。还有其他因素推动摊销。在此处查看更完整的代码。我喜欢使用“amort$end_bal npr 增加期末余额,ch_off 减少期末余额。这是更完整的代码:
n_periods <- 8
begin_bal <- 10000
yld <- .20
npr <- .09
mpr <- .10
co <- .10
period = seq(0,n_periods,1)
fin = 0
pur = 0
pmt = 0
ch_off = 0
end_bal = begin_bal
for(i in 1:n_periods){
{fin[i+1] = end_bal[i]*yld/12}
{pur[i+1] = end_bal[i]*npr}
{pmt[i+1] = end_bal[i]*mpr}
{ch_off[i+1] = end_bal[i]*co/12}
end_bal[i+1] = end_bal[i]+pur[i+1]-pmt[i+1]-ch_off[i+1]}
amort <- data.frame(period,fin,pur,pmt,ch_off,end_bal)
这给出了以下正确的输出:
print(amort,row.names=FALSE)
period fin pur pmt ch_off end_bal
0 0.0000 0.0000 0.0000 0.00000 10000.000
1 166.6667 900.0000 1000.0000 83.33333 9816.667
2 163.6111 883.5000 981.6667 81.80556 9636.694
3 160.6116 867.3025 963.6694 80.30579 9460.022
4 157.6670 851.4020 946.0022 78.83351 9286.588
5 154.7765 835.7929 928.6588 77.38823 9116.334
6 151.9389 820.4700 911.6334 75.96945 8949.201
7 149.1534 805.4281 894.9201 74.57668 8785.132
8 146.4189 790.6619 878.5132 73.20944 8624.072
我是 R 的新手,我了解它的功能之一是矩阵/向量操作。在下面的示例中,我将资产摊销超过 8 个月,其中每次付款(“pmt”)是前期余额(“end_bal”)的 10%(“mpr”)。下面的工作正常。我使用了 FOR 循环。我知道 FOR 循环在大型模型中可能会很慢,更好的解决方案是使用 R 丰富的向量/矩阵函数。但在我的示例中,我不知道如何执行此操作,因为每个月的付款都是通过参考上一期期末余额来计算的。
所以我的问题是:
- 是否有更有效的方法来执行以下操作?
- 如何将周期 0 中 pmt 的 0 替换为空格?
R 代码:
n_periods <- 8
begin_bal <- 100
mpr <- .10
# Example loan amortization
pmt = 0
end_bal = begin_bal
for(i in 1:n_periods){
{pmt[i+1] = end_bal[i]*mpr}
end_bal[i+1] = end_bal[i]-pmt[i+1]}
amort <- data.frame(period = 0:n_periods,pmt,end_bal)
amort
正确的结果:
> amort
period pmt end_bal
1 0 0.000000 100.00000
2 1 10.000000 90.00000
3 2 9.000000 81.00000
4 3 8.100000 72.90000
5 4 7.290000 65.61000
6 5 6.561000 59.04900
7 6 5.904900 53.14410
8 7 5.314410 47.82969
9 8 4.782969 43.04672
【问题讨论】:
-
这两个答案中的任何一个都没有达到您的目的吗?您应该接受最接近您期望的答案是正确的,以便问题和答案可供将来参考。 :)
标签: r