R中的循环功能

问题描述 投票:0回答:1

我试图使用自动Arima功能70个变量。为此,我需要创建70次时间序列。

dealer1 <- ts(tier2[,2], start=c(2015,8), end = c(2018,12), frequency=12)
dealer2 <- ts(tier2[,3], start=c(2015,8), end = c(2018,12), frequency=12)
dealer3 <- ts(tier2[,4], start=c(2015,8), end = c(2018,12), frequency=12)..and so on.

然后我需要再次为70个变量使用Auto Arima功能。

automatic.dealer1 = auto.arima(dealer1, ic = "aicc")
automatic.dealer2 = auto.arima(dealer2, ic = "aicc")
automatic.dealer3 = auto.arima(dealer3, ic = "aicc")... and so on

然后预测输出:

forecast.dealer1 = forecast(automatic.dealer1, h = 3)$mean
forecast.dealer2 = forecast(automatic.dealer2, h = 3)$mean
forecast.dealer3 = forecast(automatic.dealer3, h = 3)$mean

我试图在R中使用for循环,但我收到一个错误。我究竟做错了什么??

k <- 1
l <- 2

   for(i in seq(1,70)){

      dealer[k] <- ts(dealer1[,l], start=c(2015,8), end = c(2018,12), frequency=12)

      dealer[k]

      automatic <- auto.arima(dealer.[k], ic = "aicc")

      foreArima <- forecast(automatic, h=3)

      automatic

      foreArima

      k <- k+1
      l <- l+1
}

我需要为我的数据中的所有70个变量选择ARIMA模型,并显示每个变量的预测

数据样本如下:

enter image description here

r for-loop time-series arima
1个回答
0
投票

首先,您不需要循环来创建ts对象。您可以像这样创建一个多变量ts对象

myts <- ts(tier2[,2:70], , start=c(2015,8), frequency=12)

以下是在R中使用for循环的方法:

result <- numeric(ncol(myts)) #initialize a vector where the results will be stored.

for (j in 1:ncol(myts)) {
    automatic.dealer <- auto.arima(myts[,j], ic = "aicc")
    result[j] <- forecast(automatic.dealer, h = 3)$mean
}

正如附加信息:大多数时候你可以使用applysapplylapply来避免R中的循环。这样做可以提高代码的可读性和性能。

编辑:如果你想保存所有的结果,你可以将auto.arima的结果存储到一个列表中:

result <- numeric(ncol(myts))
arima.list <- list()
forecast.list <- list()

for (j in 1:ncol(myts)) {
    automatic.dealer <- auto.arima(myts[,j], ic = "aicc")
    arima.list[[j]] <- automatic.dealer
    forecast.list[[j]] <- forecast(automatic.dealer, h = 3)
    result[j] <- forecast.list[[j]]$mean
}
© www.soinside.com 2019 - 2024. All rights reserved.