# Analysis Clinic Case 005: deterministic same-sample sign reversal.
# Base R only. Run this script to verify the page example before publication.
dat <- expand.grid(a = c(-1, 1), b = c(-1, 1), e = c(-1, 1))
dat$x <- dat$a
dat$z <- dat$a + dat$b
dat$y <- 10 - dat$x + 2 * dat$z + dat$e
unadjusted <- lm(y ~ x, data = dat)
adjusted <- lm(y ~ x + z, data = dat)
x_res <- resid(lm(x ~ z, data = dat))
y_res <- resid(lm(y ~ z, data = dat))
partial <- lm(y_res ~ x_res)
print(coef(summary(unadjusted)))
print(coef(summary(adjusted)))
print(confint(unadjusted))
print(confint(adjusted))
print(c(n_unadjusted = nobs(unadjusted), n_adjusted = nobs(adjusted),
        correlation_x_z = cor(dat$x, dat$z),
        vif_x = 1 / (1 - summary(lm(x ~ z, dat))$r.squared),
        partial_slope = unname(coef(partial)["x_res"])))
stopifnot(nobs(unadjusted) == 8L, nobs(adjusted) == 8L,
          abs(coef(unadjusted)["x"] - 1) < 1e-10,
          abs(coef(adjusted)["x"] + 1) < 1e-10,
          abs(coef(adjusted)["z"] - 2) < 1e-10,
          abs(coef(partial)["x_res"] + 1) < 1e-10)
sessionInfo()
