3

我有一个循环的小问题。这是循环的代码:

for(i in 1:40) {
   ret1 <- sample(vec, 40, replace=T)
     if (i == 1) {
       val[i] = Put[i]*(1+ret1[i])
     } else (i > 1) 
     val[i] = ((val[i-1])+Put[i])*(1+ret1[i])
 }

我收到的错误消息如下:

 Error in val[i] = ((val[i - 1]) + Put[i]) * (1 + ret1[i]) : 
 replacement has length zero

这是输入数据:

val: is an empty shell to store values in 

vec <- c(43.81, -8.3, -25.12, -43.84, -8.64, 49.98, -1.19, 46.74, 31.94, 
-35.34, 29.28, -1.1, -10.67, -12.77, 19.17, 25.06, 19.03, 35.82, 
-8.43, 5.2, 5.7, 18.3, 30.81, 23.68, 18.15, -1.21, 52.56, 32.6, 
7.44, -10.46, 43.72, 12.06, 0.34, 26.64, -8.81, 22.61, 16.42, 
12.4, -9.97, 23.8, 10.81, -8.24, 3.56, 14.22, 18.76, -14.31, 
-25.9, 37, 23.83, -6.98, 6.51, 18.52, 31.74, -4.7, 20.42, 22.34, 
6.15, 31.24, 18.49, 5.81, 16.54, 31.48, -3.06, 30.23, 7.49, 9.97, 
1.33, 37.2, 22.68, 33.1, 28.34, 20.89, -9.03, -11.85, -21.97, 
28.36, 10.74, 4.83, 15.61, 5.48, -36.55, 25.94, 14.82, 2.07, 
15.83)

Put = c(6180, 6365.4, 6556.362, 6753.05286, 6955.6444458, 7164.313779174, 
7379.24319254922, 7600.6204883257, 7828.63910297547, 8063.49827606473, 
8305.40322434668, 8554.56532107708, 8811.20228070939, 9075.53834913067, 
9347.80449960459, 9628.23863459273, 9917.08579363051, 10214.5983674394, 
10521.0363184626, 10836.6674080165, 11161.767430257, 11496.6204531647, 
11841.5190667596, 12196.7646387624, 12562.6675779253, 12939.5476052631, 
13327.7340334209, 13727.5660544236, 14139.3930360563, 14563.574827138, 
15000.4820719521, 15450.4965341107, 15914.011430134, 16391.431773038, 
16883.1747262292, 17389.669968016, 17911.3600670565, 18448.7008690682, 
19002.1618951403, 19572.2267519945)

我在做什么错/不理解循环?

所有这些的目标是计算随着时间的推移投资的历史回报。我计划每年投资 X 数额的钱,并且有给定的投资回报。此外,投资是复利的。

4

1 回答 1

2

这里,else (i > 1)应该else if (i > 1)

if (i == 1) {
    val[i] = Put[i]*(1+ret1[i])   # statement 1
} else (i > 1) 
    val[i] = ((val[i-1])+Put[i])*(1+ret1[i]) # statement 2

基本上,截至目前,# statement 2对所有i. 该else声明没有任何论据。

if (...) {
    # do this 1
else if (...) {
    # do this 2 
else {
    # do this 3 
}

所以,这里i > 1# do this 3. 所以,# statement 2在if-else 条件之外。我将为所有人竞选i。但是错误发生在第一次运行时,i = 1因为val[i-1] = val[0] = numeric(0). 再numeric(0) + Put[i])*(1+ret1[i]) = numeric(0)一次。并且您将这个numeric(0)(长度为 0 的元素)分配给长度为 1 的元素,这是不可能的。

于 2013-06-16T06:54:12.290 回答