data(schools)
	
# Kreft and De Leeuw, Introducing Multilevel Modeling, Sage (1988).   
# The data set is the subsample of NELS-88 data consisting of 10 handpicked schools 
# from the 1003 schools in the full data set.
X<-schools$ses  # (socio economic status) 
Y<-schools$math #(mathematics score)
Tr<-ifelse(schools$homework > 1, 1 ,0)
Group<-schools$schid #(school ID)
# Note that when Group is missing, NULL or there is only one Group, 
# MatchPW returns the same output of the Match function (with a warning).
# Matching math scores between group of students. X are confounders.
### Match preferentially within-school 
# first match students within schools
# then tries to match remaining students between schools
 mpw <- MatchPW(Y=schools$math, Tr=Tr, X=schools$ses, Group=schools$schid, caliper=0.1)
# examine covariate balance
  bmpw<- CMatchBalance(Tr~ses,data=schools,match.out=mpw)
# proportion of matched observations
  (mpw$orig.treated.nobs-mpw$ndrops) / mpw$orig.treated.nobs 
# check drops by school
  mpw$orig.ndrops.by.group  
  
# estimate the math score difference (default is ATT)
  mpw$estimand
# complete results
   mpw
# or use summary method for main results
   summary(mpw) 
#### Propensity score matching
# estimate the propensity score (eps)
mod <- glm(Tr~ses+parented+public+sex+race+urban,
family=binomial(link="logit"),data=schools)
eps <- fitted(mod)
# eg 1: preferential within-school propensity score matching
MatchPW(Y=schools$math, Tr=Tr, X=eps, Group=schools$schid, caliper=0.1)
# eg 2: standard propensity score matching using eps
# from a logit model with dummies for schools
mod <- glm(Tr ~ ses + parented + public + sex + race + urban 
+schid - 1,family=binomial(link="logit"),data=schools)
eps <- fitted(mod)
MatchPW(Y=schools$math, Tr=Tr, X=eps, caliper=0.1)
# eg3: standard propensity score matching using ps estimated from 
# multilevel logit model (random intercept at the school level)
require(lme4)
mod<-glmer(Tr ~ ses + parented + public + sex + race + urban + (1|schid),
family=binomial(link="logit"), data=schools)
eps <- fitted(mod)
MatchPW(Y=schools$math, Tr=Tr, X=eps, Group=NULL, caliper=0.1)
 
Run the code above in your browser using DataLab