我是R新手,我希望是一個簡單的問題。我正在運行幾個嵌套循環,似乎無法獲得我期待的輸出。嵌套「for」循環在R
我想跟蹤內部循環的平衡。每次迭代代表1年。在15年的結束時,我想爲InvTotal爲4次模擬中的每一次寫最後的餘額。
我的最終產出應該是3個向量(每個投資1個),長度爲4,顯示在4次模擬結束時每個投資的最終累計值。
我的代碼如下。你可以提供任何援助將是一個巨大的幫助。
謝謝!
Investment1_Balance <- 10000
Investment2_Balance <- 10000
Investment3_Balance <- 10000
Inv1Returns <- c(0, 1000, -500, 500)
Inv2Returns <- c(0, -9000, 30000, 10000)
Inv3Returns <- c(0, 4000, -1000, -2000)
Inv1Outcome = NULL
Inv2Outcome = NULL
Inv3Outcome = NULL
Inv1Total = NULL
Inv2Total = NULL
Inv3Total = NULL
random = NULL
for (j in 1:4)
{
for (i in 1:15)
{
random[i] = runif(1, 0, 1)
Inv1Outcome[i] = if (random[i] <= .25){Investment1_Balance + Inv1Returns[1]}
else if (random[i] > .25 & random[i] <= .50){Investment1_Balance + Inv1Returns[2]}
else if (random[i] > .50 & random[i] <= .75){Investment1_Balance + Inv1Returns[3]}
else {Investment1_Balance + Inv1Returns[4]}
Inv2Outcome[i] = if (random[i] <= .20){Investment2_Balance + Inv2Returns[1]}
else if (random[i] > .20 & random[i] <= .30){Investment2_Balance + Inv2Returns[2]}
else if (random[i] > .30 & random[i] <= .70){Investment2_Balance + Inv2Returns[3]}
else ({Investment2_Balance + Inv2Returns[4]})
Inv3Outcome[i] = if (random[i] <= .50){Investment3_Balance + Inv3Returns[1]}
else if (random[i] > .50 & random[i] <= .70){Investment3_Balance + Inv3Returns[2]}
else if (random[i] > .70 & random[i] <= .90){Investment3_Balance + Inv3Returns[3]}
else ({Investment3_Balance + Inv3Returns[4]})
Investment1_Balance[i] =+ Inv1Outcome[i]
Investment2_Balance[i] =+ Inv2Outcome[i]
Investment3_Balance[i] =+ Inv3Outcome[i]
}
Inv1Total[j] = Investment1_Balance[15]
Inv2Total[j] = Investment2_Balance[15]
Inv3Total[j] = Investment3_Balance[15]
}
Inv1Total
Inv2Total
Inv3Total
這是一個巨大的幫助。謝謝,Deena! – rev201