Guest User

Untitled

a guest
Apr 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. library(tidyverse)
  2. library(broom)
  3. library(rlang)
  4.  
  5. #' Compare coefficients values across two different models
  6. #'
  7. #' @param model1 A model object (from lm for example) with a tidy method.
  8. #' @param model2 A model object (from lm for example) with a tidy method.
  9. #' @param … Bare (unquoted) coefficient names present in both models.
  10.  
  11. compare_coefs <- function(model1, model2, ...) {
  12. compare_single_coef <- function(coef) {
  13. coef_name <- quo_name(coef)
  14. t1 <- dplyr::filter(tidy(model1), term == !!coef_name)
  15. t2 <- dplyr::filter(tidy(model2), term == !!coef_name)
  16.  
  17. if (nrow(t1) == 0 || nrow(t2) == 0) {
  18. stop(paste0("Coefficient `", quo_name(coef),
  19. "` not found in one or both models."), call. = FALSE)
  20. }
  21.  
  22. diff <- t1$estimate - t2$estimate
  23. se <- sqrt(t1$std.error^2 + t2$std.error^2)
  24. statistic <- diff / se
  25.  
  26. tibble(term = coef_name,
  27. difference = diff,
  28. conf.low = diff - 1.96 * se,
  29. conf.high = diff + 1.96 * se,
  30. statistic = statistic,
  31. p.value = 2 * pnorm(abs(statistic), lower.tail = FALSE),
  32. estimate1 = t1$estimate,
  33. estimate2 = t2$estimate,
  34. method = "Z-test")
  35. }
  36. coefs <- quos(...)
  37. map_dfr(coefs, compare_single_coef)
  38. }
  39.  
  40. model <- lm(mpg ~ hp + drat, mtcars)
  41. other <- lm(mpg ~ hp * disp + drat, mtcars)
  42.  
  43. # check if there is a significant difference in `hp` and `drat` coefs
  44. # between the models
  45. compare_coefs(model, other, hp, drat)
  46.  
  47. #> # A tibble: 2 x 9
  48. #> term difference conf.low conf.high statistic p.value estimate1
  49. #> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
  50. #> 1 hp 0.0486 -0.0115 0.109 1.58 0.113 -0.0518
  51. #> 2 drat 5.00 0.796 9.21 2.33 0.0197 4.70
  52. #> # ... with 2 more variables: estimate2 <dbl>, method <chr>
Add Comment
Please, Sign In to add comment