Reputation: 353
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
}
}
Upvotes: 1
Views: 1513
Reputation: 2123
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"]
Upvotes: 2