简体   繁体   中英

Group by in Time Series Forecasting in R

I have sales data for different combinations of State + Product. I have to forecast the sales for next 3 months for each of the combination. Currently I am using ARIMA for forecasting and running the model in a loop for unique number of combination. I wanted to know in there any other simple and quick way to do this (something like group by that we use in regression) and how to implement it.

Sample Data:

State        Product         Month        Sales
  X            AA             Jan          100
  X            AA             Feb          120
  .             .              .            .
  X            AA             Dec          80
  X            AB             Jan          400
  .             .              .            .
  .             .              .            .
  X            AB             Dec          300
  Y            AA             Jan          50
  Y            AB             Jan          60                

an so on...

Current Code:

    uniqueStates = unique(data$State)
    uniqueProducts = unique(data$Product)
    for i in 1:length(uniqueStates) {
         for j in 1:length(uniqueProducts) {
              data_subset = subset(data, data$State == uniqueStates[i] & data$Product == uniqueProducts[j])
              model <- auto.arima(data_subset$Sales)
              result = forecast(model,3)
              # Store the result in a Data Frame
         }
    }

You can always make what you want a functions that returns a list, and use lapply inside a datatable combined with the by

library(forecast)
library(datatable)
library(dplyr)
data <-data %>%  as.data.table()


modelaki <- function(x) {model <- auto.arima(x)
                  result = forecast(model,3)  
         return(list(model, result))}


results <- data[, lapply(.SD, modelaki), by = State, .SDcols = "Sales"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM