Reputation: 11
I am pretty new to R. So this is a data of 183 columns and multiple rows. I am trying to do a batch forecasting however, I got the error message saying:
"Error in Raw.Data_timeseries_forecast[, i] <- forecast(Raw.Data_timeseries_fit)$mean : number of items to replace is not a multiple of replacement length"
Could anyone help me to take a look at it?
Thanks!
Raw.Data[is.na(Raw.Data)]<-0
library(forecast)
Raw.Data_timeseries<-msts(Raw.Data[,-1],seasonal.periods = c(7,12,365.25),start=1/1/2014)
ns<-ncol(Raw.Data_timeseries)
h<-365
Raw.Data_timeseries_forecast<-matrix(nrow=h,ncol=ns,byrow =FALSE)
for (i in 1:ns)
{
Raw.Data_timeseries_fit<-stlf(Raw.Data_timeseries[,i])
Raw.Data_timeseries_forecast[,i]<-forecast(Raw.Data_timeseries_fit)$mean
}
write.csv(Raw.Data_timeseries_forecast,"rawdata_stlf.csv")
Upvotes: 1
Views: 2300
Reputation: 456
The issue is that (as far as i can tell, an example of what Raw.Data looks like would help clear it up) is that your line of code :
Raw.Data_timeseries_fit<-stlf(Raw.Data_timeseries[,i])
actually returns a ts
object, with a length equal to the whole original Time-series (which I assume is longer than 365 days). You then plug that into the forcast()
function, which will output another ts
object that is of the original length. However you then try to plug that ts
object into the matrix column that has only 365 rows, and thats why it is throwing the "number of items to replace is not a multiple of replacement length" error.
looking at the documentation of the forecast function, you see that it can take both a ts and a model. Looking in the same documentation at the stlf function you see that it is actually a function that creates a stl model and then performs a forecast, so you don't actually need to call:
Raw.Data_timeseries_forecast[,i]<-forecast(Raw.Data_timeseries_fit)$mean
or you could call stlm()
instead of stlf
and then proceed to call forecast
afterwords. Either way however, I'm pretty sure the root problem is in the mismatch between the number of rows of the forecast matrix and the number of observations in the original time series object.
Upvotes: 1
Reputation: 5152
Take a look at the h
parameter inside the forecast
function, it is returning 2 times your time series length, is that what you want? If no define that explicitly.
You could also solve that problem storing the result into a list:
Raw.Data_timeseries_forecast<-list()
for (i in 1:ns)
{ # i=1
Raw.Data_timeseries_fit<-stlf(Raw.Data_timeseries[,i])
Raw.Data_timeseries_forecast[[i]]<-forecast(Raw.Data_timeseries_fit)$mean
}
Raw.Data_timeseries_forecast_f <- t(do.call("rbind",Raw.Data_timeseries_forecast))
#write.csv(Raw.Data_timeseries_forecast,"rawdata_stlf.csv")
Upvotes: 0