Saturday, 15 August 2015

how to use previous observations to forecast the next period using for loops in r? -



how to use previous observations to forecast the next period using for loops in r? -

i have made 1000 observations xt = γ1xt−1 + γ2xt−2 + εt [ar(2)]. utilize first 900 observations estimate model, , utilize remaining 100 observations predict one-step ahead. have done far:

data2=arima.sim(n=1000, list(ar=c(0.5, -0.7))) #1000 observations simulated, (ar (2)) arima(data2, order = c(2,0,0), method= "ml") #estimated parameters of model ml fit2<-arima(data2[1:900], c(2,0,0), method="ml") #first 900 observations used estimate model predict(fit2, 100)

but problem code right n.ahead=100 utilize n.ahead=1 , create 100 predictions in total. think need utilize loops this, since new user of rstudio haven't been able figure out how utilize loops create predictions. can help me this?

if i've understood correctly, want one-step predictions on test set. should want without loops:

library(forecast) data2 <- arima.sim(n=1000, list(ar=c(0.5, -0.7))) fit2 <- arima(data2[1:900], c(2,0,0), method="ml") fit2a <- arima(data2[901:1000], model=fit2) fc <- fitted(fit2a)

the arima command allows model applied new info set without parameters beingness re-estimated. fitted gives one-step in-sample forecasts.

if want multi-step forecasts on test data, need utilize loop. here illustration two-step ahead forecasts:

fcloop <- numeric(100) h <- 2 for(i in 1:100) { fit2a <- arima(data2[1:(899+i)], model=fit2) fcloop[i] <- forecast(fit2a, h=h)$mean[h] }

if set h <- 1 above same results using fitted in previous block of code. first 2 values different because approach using fitted not take business relationship of info @ end of training set, while approach using loop uses end of training set when making forecasts.

r for-loop time-series rstudio

No comments:

Post a Comment