title: Multi-steps forecasting with dplyr and do
body: <p>The do-function in dplyr lets you make a lot of cool models fast and easy, but I am struggeling to use these models for good <strong>rolling</strong> forecasts. </p>
  
  <pre><code># Data illustration
  
  require(dplyr)
  require(forecast)
  
  df &lt;- data.frame(
    Date = seq.POSIXt(from = as.POSIXct("2015-01-01 00:00:00"), 
                      to = as.POSIXct("2015-06-30 00:00:00"), by = "hour"))
  
    df &lt;- df %&gt;% mutate(Hour = as.numeric(format(Date, "%H")) + 1, 
                        Wind = runif(4320, min = 1, max = 5000), 
                        Temp = runif(4320, min = - 20, max = 25), 
                        Price = runif(4320, min = -15, max = 45)
                        )
  </code></pre>
  
  <p>My factor variable is <code>Hour</code>, my exogenous variables are <code>Wind</code> and <code>temp</code>, and the thing I want to forecast is <code>Price</code>. So, basically, I have 24 models I would like to be able to do rolling forecasts with. </p>
  
  <p>Now, my data frame contains 180 days. I would like to go back 100 days, and do a 1 day rolling forecast and then be able to compare this to the actual <code>Price</code>.</p>
  
  <p>Doing this brute force would look something like this: </p>
  
  <pre><code># First I fit the data frame to be exactly the right length
  # 100 days to start with (2015-03-21 or so), then 99, then 98.., etc. 
  n &lt;- 100 * 24
  
  # Make the price &lt;- NA so I can replace it with a forecast
  df$Price[(nrow(df) - n): (nrow(df) - n + 24)] &lt;- NA
  
  # Now I make df just 81 days long, the estimation period + the first forecast
  df &lt;- df[1 : (nrow(df) - n + 24), ]
  
  # The actual do &amp; fit, later termed fx(df)
  
  result &lt;- df %&gt;% group_by(Hour) %&gt;% do ({
    historical &lt;- .[!is.na(.$Price), ]
    forecasted &lt;- .[is.na(.$Price), c("Date", "Hour", "Wind", "Temp")]
    fit &lt;- Arima(historical$Price, xreg = historical[, 3:4], order = c(1, 1, 0))
    data.frame(forecasted[], 
               Price = forecast.Arima(fit, xreg = forecasted[3:4])$mean )
  })
  
  result
  </code></pre>
  
  <p>Now I would change <code>n</code> to 99 * 24. But it would be awesome to have this in a loop or apply, but I simply can't figure out how to do it, and also save each new forecast. </p>
  
  <p>I've tried a loop like this, but no luck yet: </p>
  
  <pre><code># 100 days ago, forecast that day, then the next, etc.
  for (n in 1:100) { 
    nx &lt;- n * 24 * 80         # Because I want to start after 80 days
    df[nx:(nx + 23), 5] &lt;- NA # Set prices to NA so I can forecast them
    fx(df) # do the function
    df.results[n] &lt;- # Write the results into a vector / data frame to save them
      # and now rinse and repeat for n + 1
    }
  </code></pre>
  
  <p>Truly awesome bonus-points for a <code>broom</code>-like solution :)</p>