test_lm_resids: Autocorrelation tests of the residuals of 'lm' models with...

View source: R/lm-resids.R

test_lm_residsR Documentation

Autocorrelation tests of the residuals of lm models with various specifications that have been fitted for a grouping variable

Description

test_lm_resids() takes a nested tibble and checks lm model residuals for autocorrelation using Breusch-Godfrey and Durbin-Watson tests.

Usage

test_lm_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 lm 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 the columns for the grouping variable, model names, and p-values for both tests.

See Also

DescTools::BreuschGodfreyTest(), DescTools::DurbinWatsonTest()

Examples


library(dplyr, warn.conflicts = FALSE)

head(ohio_covid)[ ,1:6]

models_lm <- ohio_covid %>%
  tidyr::pivot_longer(
    cols = contains("lead"),
    names_to = "lead",
    values_to = "lead_deaths"
  ) %>%
  mutate(lead = as.numeric(stringr::str_remove(lead, "deaths_lead"))) %>%
  tidyr::nest(data = c(date, cases, lead_deaths)) %>%
  arrange(lead) %>%
  mutate(model = purrr::map(data, function(df) {
    lm_poly <- lm(lead_deaths ~ cases + poly(date, 3), data = df, na.action = NULL)
    lm_poly_log <- lm(log(lead_deaths) ~ log(cases) + poly(date, 3), data = df, na.action = NULL)
    lm_quad_st <- lm(lead_deaths ~ cases + poly(date, 3), data = df, na.action = NULL)
    lm_quad_log <- lm(log(lead_deaths) ~ log(cases) + poly(date, 3), data = df, na.action = NULL)
    lm_ls <- list(lm_quad_st = lm_quad_st, lm_quad_log = lm_quad_log,
                  lm_poly = lm_poly, lm_poly_log = lm_poly_log)
    return(lm_ls)
  }
  ))

models_tbl <- select(models_lm, -data)
group_var <- "lead"
model_var <- "model"

resid_test_results <- test_lm_resids(models_tbl, group_var, model_var)
head(resid_test_results)

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