在 R 中对 ARIMA AIC 进行排序

Sorting ARIMA AIC in R

我有以下代码returns AIC 最低的模型,但我希望所有模型的 AIC 都按升序或降序排列,而不使用 R[=12 中的内置排序函数=]

sp <- rnorm(100)  ## just some toy data to make code work!
spfinal.aic <- Inf
spfinal.order <- c(0,0,0)
for (p in 1:4) for (d in 0:1) for (q in 1:4) {
  spcurrent.aic <- AIC(arima(sp, order=c(p, d, q)))
   if (spcurrent.aic < spfinal.aic) {
     spfinal.aic <- spcurrent.aic
     spfinal.order <- c(p, d, q)
     spfinal.arima <- arima(sp, order=spfinal.order)
   }
}

我希望 spfinal.order<-c(p,d,p) 是所有模型按 AIC 升序或降序排列的列表。我该怎么做?

下面的代码可以满足您的需求。由于您想要记录所有已尝试过的模型,因此在循环内不进行任何比较。矢量 aic.vec 将保存所有模型的 AIC 值,而矩阵 order.matrix 将逐列保存 ARIMA 规范。最后,我们按 AIC 值升序对两者进行排序,这样您就知道最好的模型是第一个。

sp <- rnorm(100)  ## just some toy data to make code work!
order.matrix <- matrix(0, nrow = 3, ncol = 4 * 2 * 4)
aic.vec <- numeric(4 * 2 * 4)
k <- 1
for (p in 1:4) for (d in 0:1) for (q in 1:4) {
  order.matrix[, k] <- c(p,d,q)
  aic.vec[k] <- AIC(arima(sp, order=c(p, d, q)))
  k <- k+1
  }
ind <- order(aic.vec, decreasing = FALSE)
aic.vec <- aic.vec[ind]
order.matrix <- order.matrix[, ind]

我没有使用列表来存储ARIMA规范,因为我觉得矩阵更好。目前矩阵是宽格式的,即 3 行多列。您可以转置它以获得更好的打印效果:

order.matrix <- t(order.matrix)

也许您还想将 order.matrixaic.vec 绑定在一起以便更好地呈现?这样做:

result <- cbind(order.matrix, aic.vec)
colnames(result) <- c("p", "d", "q", "AIC")

我认为这使您更容易检查。示例输出(前 5 行):

> result
      p d q      AIC
 [1,] 2 0 2 305.5698
 [2,] 3 0 3 305.8882
 [3,] 1 0 3 307.8365
 [4,] 2 1 3 307.9137
 [5,] 1 1 2 307.9952