|
| 1 | +# Verification test: Compare our manual extraction vs broom.mixed |
| 2 | +# This proves we're getting the EXACT same numbers |
| 3 | + |
| 4 | +library(mice) |
| 5 | +library(lme4) |
| 6 | + |
| 7 | +# Create test data |
| 8 | +set.seed(123) |
| 9 | +n <- 100 |
| 10 | +test_data <- data.frame( |
| 11 | + id = rep(1:20, each = 5), |
| 12 | + x = rnorm(n), |
| 13 | + y = rnorm(n) |
| 14 | +) |
| 15 | +test_data$y[sample(1:n, 20)] <- NA |
| 16 | + |
| 17 | +# Impute |
| 18 | +cat("Running imputation...\n") |
| 19 | +imp <- mice(test_data, m = 5, print = FALSE, seed = 456) |
| 20 | + |
| 21 | +# Fit mixed model |
| 22 | +cat("Fitting mixed models...\n") |
| 23 | +fit <- with(imp, lmer(y ~ x + (1 | id))) |
| 24 | + |
| 25 | +cat("\n=== METHOD 1: Our Fix (without broom.mixed) ===\n") |
| 26 | +pooled_our_fix <- pool(fit) |
| 27 | +print(summary(pooled_our_fix)) |
| 28 | + |
| 29 | +cat("\n=== METHOD 2: With broom.mixed (the old way) ===\n") |
| 30 | +library(broom.mixed) |
| 31 | +pooled_broom <- pool(fit) |
| 32 | +print(summary(pooled_broom)) |
| 33 | + |
| 34 | +cat("\n=== COMPARISON ===\n") |
| 35 | +our_results <- summary(pooled_our_fix) |
| 36 | +broom_results <- summary(pooled_broom) |
| 37 | + |
| 38 | +cat("\nIntercept estimate difference:", |
| 39 | + abs(our_results$estimate[1] - broom_results$estimate[1]), "\n") |
| 40 | +cat("Intercept SE difference:", |
| 41 | + abs(our_results$std.error[1] - broom_results$std.error[1]), "\n") |
| 42 | +cat("x coefficient estimate difference:", |
| 43 | + abs(our_results$estimate[2] - broom_results$estimate[2]), "\n") |
| 44 | +cat("x coefficient SE difference:", |
| 45 | + abs(our_results$std.error[2] - broom_results$std.error[2]), "\n") |
| 46 | + |
| 47 | +# Check if they're identical (within floating point precision) |
| 48 | +if (all.equal(our_results$estimate, broom_results$estimate, tolerance = 1e-10) == TRUE && |
| 49 | + all.equal(our_results$std.error, broom_results$std.error, tolerance = 1e-10) == TRUE) { |
| 50 | + cat("\n✅ PERFECT MATCH! Our fix produces IDENTICAL results to broom.mixed\n") |
| 51 | + cat("We're not making up numbers - we're using the exact same math!\n") |
| 52 | +} else { |
| 53 | + cat("\n❌ WARNING: Results differ!\n") |
| 54 | +} |
| 55 | + |
| 56 | +cat("\n=== MANUAL VERIFICATION ===\n") |
| 57 | +cat("Let's also manually check one imputation to prove the math:\n\n") |
| 58 | +single_fit <- getfit(fit, 1) |
| 59 | +cat("Manual fixef() extraction:\n") |
| 60 | +print(lme4::fixef(single_fit)) |
| 61 | +cat("\nManual vcov() extraction (standard errors):\n") |
| 62 | +print(sqrt(diag(vcov(single_fit)))) |
0 commit comments