R: Error: new columns would leave holes after existing columns

R: Error: new columns would leave holes after existing columns

当运行这段代码时,我得到以下错误:

Error in `[<-.data.frame`(`*tmp*`, , i, value = list(x = 0.0654882985934691,  : 
new columns would leave holes after existing columns

我正在尝试用 i 列数填充 data.frame,其中发布的 for 循环的输出应该看起来像这样(Excel 示例仅为方便起见):

目的是存储循环的输出,以便我可以在稍后阶段获得每列的平均值。

可以做些什么来实现这一目标?

library(plyr)
library(forecast)
library(vars)

x <- rnorm(70)
y <- rnorm(70)

dx <- cbind(x,y)
dx <- as.ts(dx)


# Forecast Accuracy
j = 12  #Forecast horizon
k = nrow(dx)-j #length of minimum training set

prediction <- data.frame()

for (i in 1:j) { 
  trainingset <- window(dx, end = k+i-1)
  testset <- window(dx, start = k+i, end = k+j)
  fit <- VAR(trainingset, p = 2)                       
  fcast <- forecast(fit, h = j-i+1)
  fcastmean <- do.call('cbind', fcast[['mean']])
  fcastmean <- as.data.frame(fcastmean)

  prediction[,i] <- rbind(fcastmean[,1])
 }

编辑

根据下面的评论,我编辑了上面的代码以指定 fcastmean 的第一个变量。

我得到的错误结果已经改变,现在是:

Error in `[<-.data.frame`(`*tmp*`, , i, value = c(-0.316529962287372,  : 
  replacement has 1 row, data has 0

编辑 2

以下是评论中要求的没有任何包的最低可复制版本。我认为就提出的问题而言应该是等价的。

x <- rnorm(70)
y <- rnorm(70)

dx <- cbind(x,y)
dx <- as.ts(dx)

j = 12  
k = nrow(dx)-j 

prediction <- matrix(NA,j,j)

 for (i in 1:j) { 

  fcast <- as.matrix(1:(j-i+1))
  fcastmean <- fcast

  prediction[,i] <- (fcastmean)
}

对于您的新示例,尝试

sapply(1:j, function(i) `length<-`(1:(j-i+1), j))

结果是

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
 [1,]    1    1    1    1    1    1    1    1    1     1     1     1
 [2,]    2    2    2    2    2    2    2    2    2     2     2    NA
 [3,]    3    3    3    3    3    3    3    3    3     3    NA    NA
 [4,]    4    4    4    4    4    4    4    4    4    NA    NA    NA
 [5,]    5    5    5    5    5    5    5    5   NA    NA    NA    NA
 [6,]    6    6    6    6    6    6    6   NA   NA    NA    NA    NA
 [7,]    7    7    7    7    7    7   NA   NA   NA    NA    NA    NA
 [8,]    8    8    8    8    8   NA   NA   NA   NA    NA    NA    NA
 [9,]    9    9    9    9   NA   NA   NA   NA   NA    NA    NA    NA
[10,]   10   10   10   NA   NA   NA   NA   NA   NA    NA    NA    NA
[11,]   11   11   NA   NA   NA   NA   NA   NA   NA    NA    NA    NA
[12,]   12   NA   NA   NA   NA   NA   NA   NA   NA    NA    NA    NA

`length<-`(x, j)NA 填充 x 直到长度达到 j.


您可以将 1:(j-i+1) 替换为您想要的 i 的任何功能。在 OP 的原始示例中,我猜这样的事情会起作用(未经测试):

sapply(1:j, function(i){

  trainingset <- window(dx, end = k+i-1)
  # testset   <- window(dx, start = k+i, end = k+j)
  # ^ this isn't actually used...

  fit         <- VAR(trainingset, p = 2)                       
  fcast       <- forecast(fit, h = j-i+1)
  `length<-`(fcast$mean, j)

})

function(i){...}被称为匿名函数,可以像其他的一样写。