Closed blakeflei closed 6 years ago
That was probably way too complicated.
A simpler example:
> library(forecast)
> dat <- matrix( c(1.56, 0.12, 0.44, 3.24, 0.64, 0.79, 0.46,
+ 0.41, 0.91, 0.71, 0.66, 2.97, 0.56, 3.25, 3.62),
+ nrow=5, ncol=3)
>
> ex <- matrix( c(2.84, 1.41, 2.78, 2.08, 2.41, 2.73, 2.57,
+ 2.73),
+ nrow=4, ncol=2)
>
> fit <- auto.arima(dat[,1], xreg=dat[,-1])
>
> forecast(dat[,1], model=fit, xreg=ex, h=4)
Error in stats::arima(x = x, order = order, seasonal = seasonal, xreg = xreg, :
lengths of 'x' and 'xreg' do not match
Presumably you want to do this:
forecast(fit, xreg=ex, h=4)
The first argument of forecast
should be a model. If you apply forecast
directly to data, then it will try to figure out what you meant. Here is is trying to fit the model to the data which has been passed. But then there are only 4 xreg rows but 5 observations, so it fails.
If four observations and xreg rows are used, forecast
reports there are no regressors:
> dat_update <- matrix(c(0.078, 1.69, 4.76, 3.41),
+ nrow=4, ncol=1)
>
> forecast(dat_update, model=fit, xreg=ex, h=4)
Error in forecast.Arima(fit, h = h, level = level, fan = fan) :
No regressors provided
How should one forecast
using updated data by applying an xreg arima model trained on previous data?
For example:
> dat_update <- matrix(c(dat[,1], 0.078, 1.69, 4.76, 3.41),
+ nrow=9, ncol=1) #Updated data
>
> forecast(dat_update, model=fit, xreg=ex, h=4) #Apply previous fit to updated data
Error in stats::arima(x = x, order = order, seasonal = seasonal, xreg = xreg, :
lengths of 'x' and 'xreg' do not match
The docs currently state the first argument could be a time series. This seems to work for arima models, but fails for xreg arima models.
To apply a model to a new data set, first construct the model object, then forecast. Like this
fit2 <- Arima(dat[,2], model=fit, xreg=dat[,-1])
forecast(fit2, xreg=ex)
Thank you for the clarification! I missed the model creation step.
Calling forecast on a time series object, xreg, and arima xreg model seems to fail. The goal is: 1 - Split all data into into separate train and test data. 2 - Fit the train set to create train model. 3 - Use the test set to determine error (skipped here for brevity). 4 - Apply the train model to all data to create forecast.
Example:
Generate synthetic data. Forecasts using arima with xreg will be attempted on the first column:
Split into train and test data:
Determine arima with xreg model using train data:
Forecast all exogenous variables using train models on all data:
Attempt to forecast using all data:
Only the model seems to work:
Attempt to forecast train data (should be same as above):