# Synthetic two-wave study: baseline fully observed, follow-up incomplete.
# Requires mice; no automatic installation. Multilevel/multiwave extensions
# need an imputation model that respects their dependence structure.
if (!requireNamespace('mice',quietly=TRUE)) stop('Install mice before running this example.')
set.seed(8008)
n <- 600
baseline <- rnorm(n)
arm <- rep(0:1,each=n/2)
followup <- .5*arm + .8*baseline + rnorm(n)
missing <- rbinom(n,1,plogis(-.5+.9*baseline+.6*arm))==1
full <- data.frame(arm,baseline,followup)
d <- full; d$followup[missing] <- NA
cc <- lm(followup~arm+baseline,d)
methods <- c(arm='',baseline='',followup='norm')
imp <- mice::mice(d,m=30,maxit=5,method=methods,seed=8009,printFlag=FALSE)
# Rubin pooling for a scalar arm coefficient, with normal-approximation CIs.
# The mice::pool result also supplies finite-df inference for the MAR fit.
pooled <- summary(mice::pool(with(imp,lm(followup~arm+baseline))),conf.int=TRUE)
print(pooled)
scalar <- function(delta) {
 vals <- vapply(seq_len(imp$m),function(i) {
  complete <- mice::complete(imp,i)
  # Controlled shift only for missing outcomes in the intervention arm.
  complete$followup[missing & arm==1] <- complete$followup[missing & arm==1]+delta
  f <- lm(followup~arm+baseline,complete)
  c(q=coef(f)['arm'],u=vcov(f)['arm','arm'])
 },numeric(2))
 q <- mean(vals[1,]); se <- sqrt(mean(vals[2,])+(1+1/imp$m)*var(vals[1,]))
 c(delta=delta,estimate=q,lower=q-qnorm(.975)*se,upper=q+qnorm(.975)*se)
}
cat(sprintf('Enrolled=%d; follow-up observed=%d; missing control=%d; missing intervention=%d\n',n,sum(!missing),sum(missing & arm==0),sum(missing & arm==1)))
cat(sprintf('Complete-data arm=%.3f; complete-case adjusted arm=%.3f\n',coef(lm(followup~arm+baseline,full))['arm'],coef(cc)['arm']))
print(t(vapply(c(0,-.5,-1),scalar,numeric(4))))
cat('mice version:',as.character(packageVersion('mice')),'\n')
stopifnot(imp$m==30,all(is.finite(pooled$estimate)))

# Maintainer-only export; run from repository root. Synthetic data only.
if (Sys.getenv("CLINIC_EXPORT_DATA") == "1") {
write.csv(d,'analysis-clinic/examples/case-008-shared-data.csv',row.names=FALSE,quote=FALSE,na='')
}
