Forecasting timeseries with tslm in R

Nick Mars picture Nick Mars · Feb 16, 2015 · Viewed 14.5k times · Source

I'm still new to R and am facing a problem i can't seem to resolve.

I would like to forecast my time series data. I have this year's daily numbers: y, and last year's daily number which I want to use as a predictor. The numbers show week cycles. I tried this code. (Fake numbers for clarity)

x = rnorm(60,0,1)
y = rnorm(60,0 ,1) + 2*cos(2*pi*1:60/7) + 10*x
new_x = rnorm(10,0,1) 

y <- ts(y,frequency = 7)
fit <- tslm(y ~ trend + season + x)

fcast = forecast.lm(fit, h = 10, newdata = new_x)

I get the error message :

    Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
      variable lengths differ (found for 'x')
    In addition: Warning message:
'newdata' had 10 rows but variables found have 60 rows

Any hints on what I did wrong?

Answer

user3710546 picture user3710546 · Feb 16, 2015

From your fit object:

Call:
lm(formula = formula, data = "y", na.action = na.exclude)

Coefficients:
(Intercept)        trend      season2      season3      season4      season5      season6      season7            x  
  1.1644029    0.0009672   -1.5575562   -3.6723105   -3.1824001   -1.5658857    0.0789683    0.3053541    9.9233635  

The last variable is named x. And the help for forecast.lm says newdata is an optional data.frame. You need to turn new_x into a data.frame, with x as column name.

library(forecast)

x = rnorm(60,0,1)
y = rnorm(60,0 ,1) + 2*cos(2*pi*1:60/7) + 10*x
new_x = rnorm(10,0,1) 

y <- ts(y,frequency = 7)
fit <- tslm(y ~ trend + season + x)

# You can directly use `forecast`, as `fit` is an lm object
# and you don't need `h`, as you provide new data.
fcast = forecast(fit, newdata = data.frame(x=new_x)) 

#          Point Forecast       Lo 80      Hi 80        Lo 95      Hi 95
# 9.571429     -3.1541222  -4.5886075  -1.719637  -5.37216743 -0.9360771
# 9.714286     12.5962250  11.1367496  14.055700  10.33953926 14.8529108
# 9.857143     10.5924632   9.1480030  12.036924   8.35899443 12.8259321
#10.000000     15.9419378  14.4775444  17.406331  13.67764776 18.2062278
#10.142857     -7.1887433  -8.6444741  -5.733013  -9.43963897 -4.9378477
#10.285714     -9.4133170 -10.8470152  -7.979619 -11.63014523 -7.1964887
#10.428571      2.2702132   0.8331488   3.707278   0.04818005  4.4922464
#10.571429      0.3519401  -1.1037991   1.807679  -1.89896851  2.6028487
#10.714286    -11.8348209 -13.2930857 -10.376556 -14.08963475 -9.5800070
#10.857143      1.0058209  -0.4435763   2.455218  -1.23528154  3.2469233