我有以下代码,它返回 AIC 最低的模型,但我希望所有模型的 AIC 按升序或降序排列,而不使用 R 中的内置排序函数
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.matrix
和 aic.vec
绑定(bind)在一起以获得更好的呈现效果?这样做:
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
关于r - 在 R 中对 ARIMA AIC 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998486/