Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(tidyverse)
- library(broom)
- library(rlang)
- #' Compare coefficients values across two different models
- #'
- #' @param model1 A model object (from lm for example) with a tidy method.
- #' @param model2 A model object (from lm for example) with a tidy method.
- #' @param … Bare (unquoted) coefficient names present in both models.
- compare_coefs <- function(model1, model2, ...) {
- compare_single_coef <- function(coef) {
- coef_name <- quo_name(coef)
- t1 <- dplyr::filter(tidy(model1), term == !!coef_name)
- t2 <- dplyr::filter(tidy(model2), term == !!coef_name)
- if (nrow(t1) == 0 || nrow(t2) == 0) {
- stop(paste0("Coefficient `", quo_name(coef),
- "` not found in one or both models."), call. = FALSE)
- }
- diff <- t1$estimate - t2$estimate
- se <- sqrt(t1$std.error^2 + t2$std.error^2)
- statistic <- diff / se
- tibble(term = coef_name,
- difference = diff,
- conf.low = diff - 1.96 * se,
- conf.high = diff + 1.96 * se,
- statistic = statistic,
- p.value = 2 * pnorm(abs(statistic), lower.tail = FALSE),
- estimate1 = t1$estimate,
- estimate2 = t2$estimate,
- method = "Z-test")
- }
- coefs <- quos(...)
- map_dfr(coefs, compare_single_coef)
- }
- model <- lm(mpg ~ hp + drat, mtcars)
- other <- lm(mpg ~ hp * disp + drat, mtcars)
- # check if there is a significant difference in `hp` and `drat` coefs
- # between the models
- compare_coefs(model, other, hp, drat)
- #> # A tibble: 2 x 9
- #> term difference conf.low conf.high statistic p.value estimate1
- #> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
- #> 1 hp 0.0486 -0.0115 0.109 1.58 0.113 -0.0518
- #> 2 drat 5.00 0.796 9.21 2.33 0.0197 4.70
- #> # ... with 2 more variables: estimate2 <dbl>, method <chr>
Add Comment
Please, Sign In to add comment