Search code examples
rfacebook-prophet

Make a monthly forecast for all groups with Prophet in R


How can I make a monthly forecast for different variables with Prophet ? Suppose I have a dataset with several regions (about 70, please see the table below) and I want to make a forecast for all of the regions, is it possible?

Region Month Value
Region_1 2017-01 123123
Region_1 2017-02 223333
Region_1 2017-03 11133
Region_1 2017-04 882822
Region_2 2017-01 300000
Region_2 2017-02 22333
Region_2 2017-03 23232323
Region_2 2017-04 23232323

Solution

  • You can use the freq = "month" option in making future dataframe along with dplyr. Below will predict the following 2 months.

    Region <- c('Region_1','Region_1','Region_1','Region_1','Region_2','Region_2','Region_2','Region_2')
    Value <- c(123123, 223333, 11133, 882822,300000,22333,23232323,23232323)
    Month <- as.Date(c('2017-01-01','2017-02-01','2017-03-01','2017-04-01',
                       '2017-01-01','2017-02-01','2017-03-01','2017-04-01'))
    
    df <- data.frame(Month, Region, Value)
    names(df)[1] <- 'ds'
    names(df)[3] <- 'y'
    
    install.packages("prophet")
    library(prophet)
    library(dplyr)
    
    new_df = df %>%  
      group_by(Region) %>%
      do(predict(prophet(., yearly.seasonality = TRUE), 
                 make_future_dataframe(prophet(., yearly.seasonality = TRUE), freq = "month", periods = 2))) %>%
      select(ds, Region, yhat)
    
    new_df
    

    Output:

    # A tibble: 12 x 3
    # Groups:   Region [2]
       ds                  Region          yhat
       <dttm>              <chr>          <dbl>
     1 2017-01-01 00:00:00 Region_1     123123.
     2 2017-02-01 00:00:00 Region_1     223333 
     3 2017-03-01 00:00:00 Region_1      11133.
     4 2017-04-01 00:00:00 Region_1     882822.
     5 2017-05-01 00:00:00 Region_1    -110249.
     6 2017-06-01 00:00:00 Region_1   11870506.
     7 2017-01-01 00:00:00 Region_2     300000.
     8 2017-02-01 00:00:00 Region_2      22333.
     9 2017-03-01 00:00:00 Region_2   23232323.
    10 2017-04-01 00:00:00 Region_2   23232323.
    11 2017-05-01 00:00:00 Region_2 -486859040.
    12 2017-06-01 00:00:00 Region_2  218123552.