# Rolling forecast with xreg and re-estimation

I am trying to implement, xreg into my rolling forecast with re-estimation using @robjhyndman's forecasting loop. Unfortunately, I'm facing issues with `start`and `end` for the last period (52).

``````# sample data
sample <- ts(rnorm(100, mean = 1000, sd=7), start = c(2015,1), end = c(2019,52), frequency = 52)
external <- ts(mtcars, start = c(2015,1), end = c(2019,52), frequency = 52)

#Define h --> One-step ahead (for a start, later to be increased)
h <- 1
#specify length to forecast
test  <- window(sample, start = c(2019,01), end = c(2019,52), frequency = 52)
n <- length(test) - h + 1
#provide total length of regressors available
total_xreg <- ts(external[,c(1,2,3)], start = c(2015,1), end= c(2019,12), frequency = 12)

#create empty matrix
fcmatx <- matrix(0, nrow=n, ncol=h)

# create loop
for(i in 1:n)
{
# x is the target variable, provide training data
x <- window(sample, end= c(2018,52) + (i-1)/52)
# provide xregs for training data
xregs <- window(total_xreg, end = c(2018,52) + (i-1)/52)
# provide new xregs for forecasting, assuming that xreg is available for the forecasting period
xregs2 <- window(total_xreg, start = c(2019,1) + (i-1)/52)
# limit xregs2 to show only the first line since we are only forecasting 1 step in advance
xregs3 <- xregs2[1,,drop=FALSE]
# create auto.arima model
refit.multirex <- auto.arima(x, xreg = xregs)
# forecast using regressors
fcmatx[i,] <- forecast(refit.multirex,
h=h,
xreg = xregs3
)\$mean
}
fcmattsx <- ts(fcmatx, start = c(2019,1), frequency = 52)
``````

I keep receiving this error message:

``````Error in window.default(x, ...) : 'start' must be after 'end'
``````

I tried various different approaches but couldn't get it right.

According to this loop, I am facing a second issue:
When I extend my `auto.arima` function to

``````refit.multirex <- auto.arima(x, xreg = xregs,
lambda = "auto",
``````

due to necessary transformation, I receive in addition that error message for the 4th row:

``````Error in NextMethod(.Generic) :
cannot assign 'tsp' to a vector of length 0
If I calculate it by itself for i=3 and i=5 it works perfectly. My guess is that the error message comes with the `forecast` function