循环遍历R中的时间序列数据

时间:2016-06-26 23:40:49

标签: r time-series

我想:

1)在给定数据上拟合arma模型

2)获取第二天的预测

3)向数据添加预测

4)返回1)

我编写的代码:

library(forecast)

dates<- seq(as.Date(today), by="days", length=10)
sim<- rnorm(10)
tsdata<- as.ts(cbind(as.xts(dates),sim))

temp<- tsdata

for(i in 1:10){

    Arma1[i]<-  Arima(temp, order=c(2,0,2))
    fcasts1[[i]]<- forecast(Arma1[i], h=1)  
    fore1[i]<-unlist(fcasts1[[i]]$mean[1])
    temp<- as.ts(rbind(as.xts(temp),fore1[i]))
} 

这给了我一个错误:

Error in x - fits : non-numeric argument to binary operator
In addition: Warning messages:
1: In Arma1[i] <- Arima(temp, order = c(2, 0, 2)) :
  number of items to replace is not a multiple of replacement length
2: In mean.default(x, na.rm = TRUE) :
  argument is not numeric or logical: returning NA

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我不确定你想做什么,以及预测值的timeindex是否正确,但这段代码中的循环至少应该有效:

library(xts)
library(forecast)

dates   <- seq(Sys.Date(), by="days", length=10)
sim     <- rnorm(10)
tsdata  <- xts(sim, order.by = dates)

temp.old <- tsdata
temp    <- tsdata
Arma1   <- list(10)
fcasts1 <- list(10)
fore1   <- list(10)
temp    <- list(10)

for(i in 1:10){
  Arma1[[i]]    <-  Arima(temp.old, order=c(2,0,2))
  fcasts1[[i]]  <- forecast(Arma1[[i]], h=1)  
  fore1[i]      <- unlist(fcasts1[[i]]$mean)
  temp[i]    <- as.xts(fore1[[i]], order.by = dates[i])
}