Shraddha - 10 months ago 57

R Question

I am trying to do a holt winters forecast for a dataset which is of this pattern..

`>Insample`

`Region Week Sales`

x 01/1/2013 200

x 08/1/2013 250

x 15/1/2013 185

x 22/1/2013 375

y 01/1/2013 155

y 08/1/2013 160

y 15/1/2013 225

y 22/1/2013 200

z 01/1/2013 345

z 08/1/2013 285

z 15/1/2013 300

z 22/1/2013 325

I have been following the little book of R and Rob Hyndman's Otexts...

But to my understanding, we can consider only one dataset at a time. But considering the number of regions I have here in this dataset, I might have to store data for each region separately in the workspace and read from there everytime. That doesn't seem efficient. Is there any way to handle this?

I had the same issue with

`arima`

`arima_fits <- group_by(Insample, Region) %>% do(fit=auto.arima(.$Sales))`

But this doesn't seem to help with HW.

`hw_fits <- group_by(Insample, Region) %>% do(fit=hw(.$Sales))`

Error:

`Error in ets(x, "AAA", alpha = alpha, beta = beta, gamma = gamma, damped = damped, : `

Nonseasonal data

Since I got this error, I tried doing it per region (univariate series - sales of 1 region) and it worked fine.

`fit1 <- hw(Region1, seasonal="additive")`

Any suggestions??

Answer Source

```
Insample <- read.table(text="Region Week Sales
x 01/1/2013 200
x 08/1/2013 250
x 15/1/2013 185
x 22/1/2013 375
y 01/1/2013 155
y 08/1/2013 160
y 15/1/2013 225
y 22/1/2013 200
z 01/1/2013 345
z 08/1/2013 285
z 15/1/2013 300
z 22/1/2013 325",sep="",header=T,stringsAsFactors=F)
library(stringr)
library(dplyr)
library(forecast)
Insample %>%
group_by(Region) %>%
mutate(year= as.numeric(str_extract(Week, perl('(?<=\\/)\\d+$'))), #extract year from Week column
tsR= ts(Sales, start=year, frequency=52)) %>%
do(data.frame(fc = forecast(ets(.$tsR))))
```