test_fable_resids: Autocorrelation test of the residuals of dynamic regression...

View source: R/test-fable-resids.R

test_fable_residsR Documentation

Autocorrelation test of the residuals of dynamic regression fable models with various specifications that have been fitted for a grouping variable

Description

test_fable_resids() takes a nested tibble and checks fable model residuals for autocorrelation using the Ljung-Box test.

Usage

test_fable_resids(mod_tbl, grp_col, mod_col)

Arguments

mod_tbl

tibble with a grouping variable and a nested list column with a list of model objects for each grouping variable value

grp_col

name of the grouping variable column

mod_col

name of the nested list column with the lists of fable model objects

Details

P-values less than 0.05 indicate autocorrelation is present. If all p-values round to less than 0.000, then a single "0" will be returned.

Value

An unnested tibble with columns for the grouping variable, model names, and p-values from the Ljung-Box test.

See Also

feasts::ljung_box()

Examples


library(dplyr, warn.conflicts = FALSE)
library(fable, quietly = TRUE)
library(furrr, quietly = TRUE)
plan(multisession)

head(ohio_covid)[,1:6]

models_dyn <- ohio_covid[ ,1:7] %>%
  tidyr::pivot_longer(
    cols = contains("lead"),
    names_to = "lead",
    values_to = "lead_deaths"
  ) %>%
  select(date, cases, lead, lead_deaths) %>%
  mutate(lead = as.numeric(stringr::str_remove(lead, "deaths_lead"))) %>%
  tsibble::as_tsibble(index = date, key = lead) %>%
  tidyr::drop_na() %>%
  tidyr::nest(data = c(date, cases, lead_deaths)) %>%
  # Run a regression on lagged cases and date vs deaths
  mutate(model = furrr::future_map(data, function(df) {
    model(.data = df,
          dyn_reg = ARIMA(lead_deaths ~ 1 + cases),
          dyn_reg_trend = ARIMA(lead_deaths ~ 1 + cases + trend()),
          dyn_reg_quad = ARIMA(lead_deaths ~ 1 + cases + poly(date, 2))
    )
  }
  ))
# shut down workers
plan(sequential)

dyn_mod_tbl <- select(models_dyn, -data)

fable_resid_res <- test_fable_resids(dyn_mod_tbl, grp_col = "lead", mod_col = "model")
head(fable_resid_res)

ercbk/ebtools documentation built on Feb. 22, 2025, 1:51 p.m.