Search code examples
rdataframetime-seriesforecasting

Save fitted and predicted values to data frame in r


I am trying to extract the fitted and predicted values from the different classes of the object. But when I save them to a column in a data frame I got a column with NA. I tried to fix that by making the fitted value numeric, a data frame. But when it comes to saving the values in a data frame I still got the NA or errors. Adjusting the number of rows did neither helped.

This is my code: library(forecast)

#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =3, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =3, nrow=4))
colnames(df1)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1= arima(b)
model_2=naive(b)
model_3=HoltWinters(ts(b, frequency=4))


#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$xhat 


#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#



#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted
df2[,3]=Predictedmodel_2$fitted
df2[,4]=Predictedmodel_3$fitted

Can somebody help me pls?


Solution

  • You are trying to combine lists, but you want data frames. To understand the difference, see this post: What is difference between dataframe and list in R?. To fix it, store the objects as data frames rather than lists before combining.

    df1 = as.data.frame(11:20)
    df1.Temp1 = as.data.frame(Predictedmodel_1$fitted)
    df1.Temp2 = as.data.frame(Predictedmodel_2$fitted)
    df1.Temp3 = as.data.frame(Predictedmodel_3$fitted)
    
    df1 = cbind(df1,df1.Temp1,df1.Temp2,df1.Temp3)
    
    colnames(df1) = c("Col1","col2","col3","col4")