【问题标题】:Apply a cumulative function to a matrix by row with R使用 R 逐行将累积函数应用于矩阵
【发布时间】:2017-08-30 18:26:33
【问题描述】:

我有一个投资组合,第一年年初的初始余额为 100,000 美元。我想说,每年花费上一年年末余额的 4%,然后对剩余的差额应用投资组合增长率,以获得情景中下一年的 EOY 余额。我有一个市场增长率矩阵,每个场景对应一行,该场景的每一年对应一列。

例如,假设第一行/场景的增长率为 4 年(列):1.1、0.9、0.95 和 1.2。

我的消费率为上一年的 EOY 余额(或第一年的初始余额)的 4%。我的初始余额是 100,000 美元。在第一年年底,我的余额为 100,000 美元 - (.04 * 100,000) * 1.1,即 105,600 美元。

在这种情况的第二年年底,我的余额将是 105,600 美元 - (.04 * 105,600) * 0.9 或 108,518。我想建立一个EOY余额矩阵。

我可以在 R 中使用循环来执行此操作,如下所示。我正在寻找一种更快、更简单的方法来避免循环。有什么建议吗?

我尝试了各种应用功能,但均未成功。谢谢!

rows <- 2
cols <- 4

# create 4 years (columns) of portfolio growth factors for each of two scenarios (rows)
marketReturns <- matrix(c(.9,1.1,.8,1.2,1.3,.95,1.3,.95),nrow=2,ncol=cols,byrow=TRUE)
bal <- matrix(0,rows,cols)

print("Market Growth Rates")
print(marketReturnsM)

initPortBal <- 10000   # initial portfolio balance

# create a matrix of annual end-of-year portfolio balances by subtracting a spending percentage
# from the previous year's EOY balance, then applying this year's portfolio growth factor
# gain or loss to the difference.
# For the first year, use the initial portfolio balance in place of the previous year's
# EOY balance.

spend = .04  # spend 4% of the previous year's EOY balance

for (i in (1:rows)){
  for (j in (1:cols)) {
    if (j > 1) {
      bal[i,j] <- (bal[i,j-1] - (spend * bal[i,j-1])) * marketReturns[i,j]
    } else {     # else use initial portfolio balance for last year's EOY balance
      bal[i,j] <- (initPortBal - (spend * initPortBal)) * marketReturns[i,j]
    }
  } # end j for loop
} # end i for loop

print("End of Year Balances")
print(bal)

[1] "Market Growth Rates"
     [,1] [,2] [,3] [,4]
[1,]  0.9 1.10  0.8 1.20
[2,]  1.3 0.95  1.3 0.95

[1] "End of Year Balances"
[,1]     [,2]      [,3]     [,4]
[1,]  8640  9123.84  7007.109  8072.19
[2,] 12480 11381.76 14204.436 12954.45

【问题讨论】:

  • 我没有读过这个,但从标题中,你可能想看看matrixStats 包。有许多累积函数可用。

标签: r matrix apply


【解决方案1】:

(x-(0.4*x))*0.9 这样的操作可以简化为x*0.9*(1-0.4)。这意味着我们可以将spendmarketReturns 组合成一个矩阵marketReturns*(1-spend),然后使用cumprodapply 求这个矩阵在列上的累积乘积。然后我们需要做的就是将该矩阵乘以初始余额。

t(apply(marketReturns*(1-spend),1,cumprod))*initPortBal

【讨论】:

  • 故事的寓意:不要让编码完全让你对数学视而不见。
【解决方案2】:

您可以将一年到下一年的进展表述为简单的乘法:

bal[i,j] <- bal[i,j-1] * (1 - spend) * marketReturns[i,j]

因此您只需要您的净收益的累积乘积:

netReturns <- (1 - spend) * marketReturns
cumNetReturns <- t(apply(netReturns, 1, cumprod))
bal <- initPortBal * cumNetReturns

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多