# Case 012: controlled teaching examples; base R only.
dat <- expand.grid(c = c(-1,1), a = c(-1,1), b = c(-1,1), e = c(-1,1), d = c(-1,1))
dat$x <- dat$c + dat$a
dat$m <- dat$x + dat$b
dat$y <- dat$x + 2*dat$c + 2*dat$m + dat$e
fits <- list(unadjusted=lm(y~x,dat), confounder=lm(y~x+c,dat), mediator=lm(y~x+c+m,dat))
print(sapply(fits, function(f) coef(f)["x"]))
# A separate causal world: conditioning on a common effect.
dat$x2 <- dat$a
dat$y2 <- dat$x2 + dat$b + dat$e
dat$k <- dat$x2 + dat$b + dat$d
collider_fits <- list(unadjusted=lm(y2~x2,dat), collider=lm(y2~x2+k,dat))
print(sapply(collider_fits, function(f) coef(f)["x2"]))
stopifnot(all(abs(sapply(fits,function(f) coef(f)["x"])-c(4,3,1))<1e-10),
 all(abs(sapply(collider_fits,function(f) coef(f)["x2"])-c(1,.5))<1e-10),
 all(sapply(c(fits,collider_fits),nobs)==32L))
sessionInfo()
