Time series regression

image

Can someone please help me fix the error:

library(lubridate)
arrival$Date<- as.Date(paste0(arrival$Date,"01"), format = "%YM%m%d")

arrival_ts <- ts(Actual.Countsnew, start= c(1921,04), end=c(2021, 05), frequency = 12)
library("forecast")
t <- time(arrival_ts)
lm1 <- tslm(arrival_ts ~ t)
tsforecast <- forecast(lm1, h=50)

**Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : object is not a matrix**

**'newdata' had 50 rows but variable found had 1 rowError in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : **
**  object is not a matrix**

plot(tsforecast)

Thank you

You're trying to fit a regression model with a time trend, and you've generated the trend variable for the training period, but not for the test period. In other words, the forecast() function doesn't know what the values of t are in the future unless you tell it.

You could fix the problem by including a newdata argument in the call to forecast() which would include the future values of the t variable.

But a simpler fix is to use the built-in trend variable which is recognized by both tslm() and forecast() as a linear time trend and the values are generated for you.

library(forecast)

arrival_ts <- ts(rnorm(1200), start= c(1921,04), end=c(2021, 05), frequency = 12)
lm1 <- tslm(arrival_ts ~ trend)
tsforecast <- forecast(lm1, h=50)

Created on 2021-09-07 by the reprex package (v2.0.1)

2 Likes

it works now, thank you very much for your help

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it: