[英]R - how to "insert" a value into a row for a fill-in matrix
您好,這是一個更可重復的示例。
我有一個R腳本,該腳本大量借鑒了這篇博文,我正在嘗試對每個模擬矩陣的構造方式進行一些修改。
我對 R 中的 for 循環非常不滿意,所以我需要一些幫助來解決這個問題。
我希望做的是找到一種方法為某一行(或多行)注入一個值(重新基線)......也許我想太多了,錯過了一些明顯的東西?
# starting cash for each "simulation"
principle = 100
#starting inflation assumption
inflation = .05
#starting returns
returns = .02
# number of time units (lets say months)
n.obs = 5
# number of simulations (columns)
n.sim = 5
# time I retire and get access to 401k
t_retire = 4
# amount of money available to be added to my principal at t==t_retire
retire = 100
# simulate cases - they're all the same in this example
nav = matrix(start.capital, n.obs + 1, n.sim)
for (j in 1:n.obs) {
nav[j + 1, ] = (nav[j, ] * (1 + returns - inflation))
}
我想編輯這個 for 循環,將“退休”值添加到我現有的“原則”中,行 (t_retire) = 4。
以最小的例子,我認為這可能是所需要的:
nav = matrix(start.capital, n.obs + 1, n.sim)
for (j in 1:n.obs) { if(j==t_retire){nav[j, ] <- nav[j-1] + retire}
nav[j + 1, ] = (nav[j, ] * (1 + returns - inflation))
}
nav
#----------------------
[,1] [,2] [,3] [,4] [,5]
[1,] 100000.00 100000.00 100000.00 100000.00 100000.00
[2,] 97000.00 97000.00 97000.00 97000.00 97000.00
[3,] 94090.00 94090.00 94090.00 94090.00 94090.00
[4,] 94190.00 94190.00 94190.00 94190.00 94190.00
[5,] 91364.30 91364.30 91364.30 91364.30 91364.30
[6,] 88623.37 88623.37 88623.37 88623.37 88623.37
如果這不是所需的修改,那么至少它可以構成澄清的基礎。 並不是說 R 用單個值的副本填充行的習慣在這里起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.