将模型应用于多个时间序列

问题描述 投票:4回答:2

比方说,我有多个时间序列,我想对其进行预测。如果我有合适的时间序列对象,我可以(为了举例)拟合一个ARIMA模型等等。但是,我知道一定有一个简单的方法可以自动完成这个过程,当所有的序列都在一个 xts 对象(撇开不同的变量可能需要不同的ARIMA模型不谈,这可能是另一个时间的问题)。

一些样本数据作为xts对象(六个不同企业的日收入)。

library(xts)

ts <- structure(c(534L, 549L, 636L, 974L, 848L, 895L, 1100L, 1278L, 
1291L, 1703L, 1532L, 533L, 619L, 642L, 939L, 703L, 759L, 1213L, 
1195L, 1153L, 1597L, 1585L, 649L, 597L, 628L, 924L, 703L, 863L, 
1261L, 1161L, 1212L, 1616L, 1643L, 583L, 694L, 611L, 891L, 730L, 
795L, 1242L, 1210L, 1159L, 1501L, 1702L, 513L, 532L, 580L, 917L, 
978L, 947L, 1227L, 1253L, 1121L, 1697L, 1569L, 646L, 636L, 516L, 
869L, 980L, 937L, 1173L, 1203L, 1204L, 1511L, 1640L), .Dim = c(11L, 
6L), .Dimnames = list(NULL, c("Americas_Globe", "Americas_Lucky", 
"Americas_Star", "Asia_Star", "EuroPac_Globe", "EuroPac_Lucky"
)), index = structure(c(1367384400, 1367470800, 1367557200, 1367643600, 
1367730000, 1367816400, 1367902800, 1367989200, 1368075600, 1368162000, 
1368248400), tzone = "", tclass = c("POSIXlt", "POSIXt")), .indexCLASS = c("POSIXlt", 
"POSIXt"), tclass = c("POSIXlt", "POSIXt"), .indexTZ = "", tzone = "", class = c("xts", 
"zoo"))

我可以从这个对象中提取一个时间序列...

ts.amerglob <- ts[,1] #Extract the "Americas_Global company time-series

并对其进行建模,然而(为了举例,拟合一个ARIMA模型)。

ts.ag.arima <- arima(ts.amerglob, order=c(0,1,1))

并进行预测

ts.ag.forecasts <- forecast.Arima(ts.ag.arima, h=5)

但是,如果我想为这6家公司中的每一家公司都这样做呢?ts 对象?

在拟合标准回归模型时,我曾用by()对数据的子集做过类似的事情。但在这里应用这种方法似乎并不奏效。

co.arima <- by(ts, ts[,1:6],
    function(x) arima(x, order=c(1,0,1)))

返回一个关于序列长度的错误。

error in tapply(seq_len(11L), list(INDICES = c(534L, 549L, 636L, 974L,  : 
  arguments must have same length

有没有什么简单的方法可以一次将时间序列模型应用于多个时间序列并提取相关信息?最终,我想做的是将这些时间序列中的每一个序列的预测放到一个data.frame或矩阵中(但如果能在建模过程中的中间步骤中做同样的事情就更好了,比如说...)。自动.阿里玛() 每个时间序列的输出)...)

r xts
2个回答
4
投票

只需使用 lapply 在这里,如果您想对每个时间序列使用不同的顺序参数,可以使用

res <- lapply(dat.ts,arima,order=c(1,0,1))

如果你想对每个时间序列使用不同的顺序参数,你可以使用 Mapmapply:

## generate a random list of orders
orders <- lapply(seq_len(ncol(dat.ts)),function(x)sample(c(0,1),3,rep=T))
## for each serie compute its arima with its corresponding order
Map(function(x,ord)arima(x,ord),as.list(dat.ts),orders)

编辑: 使用auto.arima fom获取订单 forecast 包。

注:我很少使用这个包,所以我不确定最终的结果。 我在这里展示的只是使用 lapply:

orders <- lapply(dat.ts,function(x){
             mod <- auto.arima(x)
             mod$arma[c(1, 6, 2, 3, 7, 4, 5)][1:3]
 })
$Americas_Globe
[1] 0 1 0
$Americas_Lucky
[1] 0 1 0
$Americas_Star
[1] 0 1 1
$Asia_Star
[1] 0 1 0
$EuroPac_Globe
[1] 0 1 0
$EuroPac_Lucky
[1] 0 1 0
© www.soinside.com 2019 - 2024. All rights reserved.