我正尝试填补向量的波动性,如下所示,但无法正常工作。
volatility<-c(var(logReturnPowerTwo/100))
logReturn^2->logReturnPowerTwo
for(i in logReturnPowerTwo){
riskMetric=0.94*volatility[i]+0.06*logReturnPowerTwo[i]/100
volatility<-c(volatility, riskMetric)
}
这是logReturn中的值:
[1] 8.082460e+00 2.401705e+01 1.119498e+00 7.068524e+00 2.928743e-02
[6] 1.474207e-01 9.269498e-01 1.054123e+00 4.134153e-01 3.968767e-01
[11] 4.749725e-02 1.912778e+00 1.628902e-01 7.440921e-04 1.675310e+00
[16] 8.284387e-02 2.481601e-01 3.376052e-02 4.678596e-01 4.925718e-01
[21] 3.075315e-01 3.063732e-01 3.105814e+00 1.300171e-01 2.143629e-02
[26] 6.765015e-01 3.899252e-01 1.793656e+00 1.385385e+00 7.402517e-01
[31] 3.995929e-02 6.678446e-01 3.636821e+00 3.061978e+00 3.467540e+00
[36] 3.694082e-02 3.089059e-01 3.024624e+00 5.801600e-01 2.029709e+00
[41] 1.131224e-02 3.237008e-01 3.580909e-01 9.907510e-01 4.386155e-01
[46] 5.228942e-02 6.284059e+00 1.947789e+01 2.228073e+00 6.846287e+00
[51] 3.449576e-01 3.926376e+00 3.059677e+00 5.931418e+00 3.257441e+00
[56] 1.640565e-01 3.885919e+00 1.259141e+00 6.376983e+00 6.060862e+00
[61] 2.128952e-01 1.150691e+00 1.573736e+00 1.224593e+01 7.345780e-02
[66] 1.828631e+01 3.979757e+00 6.535446e-01 7.193116e+00 4.480096e-02
这是波动性的结果:
[1] 0.003646857 NA NA 0.008277521 NA
[6] 0.008277521 0.008277521 0.008277521 NA 0.008277521
[11] 0.008277521 NA NA NA NA
[16] NA 0.007869323 NA NA 0.007869323
[21] NA NA NA NA NA
[26] 0.008277521 0.007869323 0.007869323 0.008277521 0.008277521
[31] NA NA NA 0.008337040 NA
[36] 0.008277521 NA 0.008277521 NA 0.008277521
[41] NA NA 0.008277521 NA NA
[46] 0.008337040 NA NA 0.008277521 NA
[51] 0.008277521 0.008277521 0.008277521 NA 0.008277521
[56] 0.008277521 0.008277521 NA NA NA
[61] 0.008277521 NA NA NA 0.008277521
[66] 0.008277521 NA NA 0.008277521 NA
答案 0 :(得分:1)
我们可以做到无循环
out <- 0.94*volatility+0.06*logReturnPowerTwo/100
out
#[1] 6.910518 7.217413 6.872074 6.901301
logReturn <- c(8.082460e+00, 2.401705e+01, 1.119498e+00, 7.068524e+00)
logReturn^2->logReturnPowerTwo
volatility<-c(var(logReturnPowerTwo/100))
答案 1 :(得分:1)
如果您更喜欢使用for
循环,则可能需要以下内容,其中for(i in logReturnPowerTwo)
应替换为for(i in seq_along(logReturnPowerTwo))
:
for(i in seq_along(logReturnPowerTwo)){
riskMetric=0.94*volatility[i]+0.06*logReturnPowerTwo[i]/100
volatility<-c(volatility, riskMetric)
}
否则,您也可以使用
for(i in logReturnPowerTwo){
riskMetric=0.94*volatility[which(logReturnPowerTwo==i)]+0.06*i/100
volatility<-c(volatility, riskMetric)
}
带有Dummay数据的示例
logReturnPowerTwo <- 100:120
logReturn <- 30:40
volatility<-c(var(logReturnPowerTwo/100))
logReturn^2->logReturnPowerTwo
for(i in seq_along(logReturnPowerTwo)){
riskMetric=0.94*volatility[i]+0.06*logReturnPowerTwo[i]/100
volatility<-c(volatility, riskMetric)
}
> volatility
[1] 0.003850 0.543619 1.087602 1.636746 2.191941 2.754025 3.323783 3.901956 4.489239 5.086284 5.693707
[12] 6.312085