learnerX
learnerX

Reputation: 1082

How to store forecasted values using 'forecast' library in R into a CSV file?

I have fitted a TBATS model around my seasonal time-series data and used the forecast package to obtain predictions. My R code is:

library("forecast")
data = read.csv("data.csv")
season_info <- msts(data,seasonal.periods=c(24,168))
model <- tbats(season_info)
forecasted <- forecast.tbats(best_model,h=24,level=90)
forecasted

Now, I have a variable called 'forecasted' that outputs as such:

> forecasted
         Point Forecast    Lo 90    Hi 90
6.940476       5080.641 4734.760 5426.523
6.946429       5024.803 4550.111 5499.496
6.952381       4697.625 4156.516 5238.733
6.958333       4419.105 3832.765 5005.446
6.964286       4262.782 3643.528 4882.037
6.970238       4187.629 3543.062 4832.196
6.976190       4349.196 3684.444 5013.947
6.982143       4484.108 3802.574 5165.642
6.988095       4247.858 3551.955 4943.761
6.994048       3851.379 3142.831 4559.927
7.000000       3575.951 2855.962 4295.941
7.005952       3494.943 2764.438 4225.449
7.011905       3501.354 2760.968 4241.739
7.017857       3445.563 2695.781 4195.345

I need to gather the forecasted values from the column 'Forecast' and store it in a CSV file. I tried to read the page for the TBATS and 'forecast' method online, but they do not say how a particular column of forecasted values could be extracted, ignoring the other columns such as 'Hi' 'Lo' and 'Point'.

I'm looking for this output in my CSV:

hour,forecasted_value
0,5080.641
1,5024.803
2,4697.625
...

Upvotes: 1

Views: 3990

Answers (3)

Karthi V
Karthi V

Reputation: 79

use mean function for getting your Point Forecast

library("forecast")

data = read.csv("data.csv")

season_info <- msts(data,seasonal.periods=c(24,168))

model <- tbats(season_info)

forecasted <- (forecast.tbats(best_model,h=24,level=90))$mean

or

forecasted$mean

Upvotes: 0

J.R.
J.R.

Reputation: 3878

You can obtain the output shown by using print():

library("forecast")
data = read.csv("data.csv")
season_info <- msts(data,seasonal.periods=c(24,168))
model <- tbats(season_info)
forecasted <- forecast.tbats(best_model,h=24,level=90)
dfForec <- print(forecasted)

this will give you the data.frame, now you can pick out the columns you want, ie. dfForec[, 1] for only the point-forecast, then use write.csv(dfForec[, 1, drop = FALSE], ...) to write it to a flat file.

Upvotes: 2

Pierre L
Pierre L

Reputation: 28441

They are stored in three parts. You can look at the object structure with str(ret):

library(forecast)
fit <- tbats(USAccDeaths)
ret <- forecast(fit)
ret$upper # Upper interval
ret$lower # Lower interval
ret$mean  # Point forecast

Upvotes: 3

Related Questions