我编写了一个函数来迭代预测使用dyn软件包构建的模型,我希望对此有一些反馈。有一个更好的方法吗?是否有人为dyn类(或dynlm类)编写了规范的“预测”方法,或者我在这里冒险进入未知领域?

ipredict <-function(model, newdata, interval = "none",
        level = 0.95, na.action = na.pass, weights = 1) {
 P<-predict(model,newdata=newdata,interval=interval,
  level=level,na.action=na.action,weights=weights)
 for (i in seq(1,dim(newdata)[1])) {
  if (is.na(newdata[i])) {
   if (interval=="none") {
    P[i]<-predict(model,newdata=newdata,interval=interval,
     level=level,na.action=na.action,weights=weights)[i]
    newdata[i]<-P[i]
   }
   else{
    P[i,]<-predict(model,newdata=newdata,interval=interval,
     level=level,na.action=na.action,weights=weights)[i,]
    newdata[i]<-P[i,1]
   }
  }
 }
 P_end<-end(P)[1]*frequency(P)+(end(P)[2]-1) #Convert (time,period) to decimal time
 P<-window(P,end=P_end-1*frequency(P)) #Drop last observation, which is NA
 return(P)
}


用法示例:

library(dyn)
y<-arima.sim(model=list(ar=c(.9)),n=10) #Create AR(1) dependant variable
A<-rnorm(10) #Create independant variables
B<-rnorm(10)
C<-rnorm(10)
Error<-rnorm(10)
y<-y+.5*A+.2*B-.3*C+.1*Error #Add relationship to independant variables
data=cbind(y,A,B,C)

#Fit linear model
model.dyn<-dyn$lm(y~A+B+C+lag(y,-1),data=data)
summary(model.dyn)

#Forecast linear model
A<-c(A,rnorm(5))
B<-c(B,rnorm(5))
C<-c(C,rnorm(5))
y=window(y,end=end(y)+c(5,0),extend=TRUE)
newdata<-cbind(y,A,B,C)
P1<-ipredict(model.dyn,newdata)
P2<-ipredict(model.dyn,newdata,interval="prediction")

#Plot
plot(y)
lines(P1,col=2)

最佳答案

R核心中的predict.Arima具有n.ahead参数来预测n下一步,看来这是您与dyn一起寻找的东西,但predict.dyn当前不支持该功能。要获得这种效果,您必须在执行操作时反复调用dyn$whatever

关于r - 迭代预测dyn模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4856555/

10-12 02:01