循环 - 替换长度为零

时间:2013-06-16 06:31:29

标签: r loops if-statement

我对循环有点问题。这是循环的代码:

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金额,并且投资有一定的回报。此外,投资正在复合投资。

1 个答案:

答案 0 :(得分: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都会执行ielse语句不带任何参数。

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的元素,这是不可能的。