tylerdrod
tylerdrod

Reputation: 1

How can I apply auto.arima by group?

Let's say I have the following Data Frame:

column_a<-c("A","A","A","B","B","B","C","C","C")
column_b<-c("AA","AA","AA","BB","BB","BB","CC","CC","CC")
column_c<-c("AAA","BBB","AAA","AAA","AAA","BBB","CCC","AAA","CCC")
Quarter<- c(3/31/2020,6/30/2020,9/30/2020,3/31/2020,6/30/2020,9/30/2020,3/31/2020,6/30/2020,9/30/2020)
Amount<-c(5,10,10,20,20,30,25,30,30)

data.frame(column_a,column_b,column_c,Quarter,Amount)

Lets say the combination of column A, B, and C is an individual product. Is there a way I can group A,B and C in r and apply auto.arima to Predict the next 3 quarters Amount? Do I have to Concatenate them into one column in order to make this work?

Upvotes: 0

Views: 703

Answers (1)

Rob Hyndman
Rob Hyndman

Reputation: 31800

Use the tsibble and fable packages. Like this:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tsibble)
#> 
#> Attaching package: 'tsibble'
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, union
library(fable)
#> Loading required package: fabletools

df <- tibble(
    column_a = c("A","A","A","B","B","B","C","C","C"),
    column_b = c("AA","AA","AA","BB","BB","BB","CC","CC","CC"),
    column_c = c("AAA","BBB","AAA","AAA","AAA","BBB","CCC","AAA","CCC"),
    Quarter =  c("3/31/2019","6/30/2019","9/30/2019","12/31/2019","3/31/2020","6/30/2020","9/30/2020","12/31/2020","3/31/2021"),
    Amount = c(5,10,10,20,20,30,25,30,30)
  )
df <- df %>%
  mutate(Quarter = yearquarter(lubridate::mdy(Quarter))) %>%
  as_tsibble(index=Quarter, key=column_c) %>%
  fill_gaps()

df %>%
  model(ARIMA(Amount))
#> # A mable: 3 x 2
#> # Key:     column_c [3]
#>   column_c        `ARIMA(Amount)`
#>   <chr>                   <model>
#> 1 AAA              <ARIMA(0,2,0)>
#> 2 BBB              <ARIMA(0,0,0)>
#> 3 CCC      <ARIMA(1,0,0) w/ mean>

Created on 2021-02-04 by the reprex package (v1.0.0)

See OTexts.com/fpp3 for more information about using fable for forecasting. The fable::ARIMA() function is equivalent to forecast::auto.arima().

Upvotes: 1

Related Questions