Skip to content

Instantly share code, notes, and snippets.

Created May 21, 2012 03:45
Show Gist options
  • Save anonymous/2760470 to your computer and use it in GitHub Desktop.
Save anonymous/2760470 to your computer and use it in GitHub Desktop.
Two ways of doing genetic matching in R
# Two Matching Methods
# Method 1 - GenMatch()
library(Matching)
covars <- c("sick", "age", "literate", "employment", "public", "urban", "poverty", "owndwell")
X <- as.matrix(collapsed.data[,covars])
W <- collapsed.data$treated_any
g.weights <- GenMatch(Tr=W, X=X, BalanceMatrix=X, estimand="ATT", M=1,print.level=0,max.generations=1,hard.generation.limit=TRUE)
g.weights$matches
# col 1 is row number of treated observations in matched dataset
# col 2 is row number of control observations
# col 3 is the weight that each matched pair is given
nrow(g.weights$matches) # 187 matched treated units
# Method 2 - MatchIt() confirms the above
library(MatchIt)
m.out <- matchit(treated_any ~ sick + age + literate + employment + public + urban + poverty + owndwell, collapsed.data, method="genetic")
m.data <- match.data(m.out, group="treat")
nrow(m.data) # 187 matched treated units -- good, confirms above
m.treat <- as.data.frame(m.data$lga_id)
m.data <- match.data(m.out, group="control")
nrow(m.data) # 104 matched control units
m.control <- as.data.frame(m.data$lga_id)
matched.ids <- rbind(m.treat,m.control)
matched.ids # 291 matched LGAs (187 treatment and 104 control)
colnames(matched.ids) <- c("lga_id")
matched.ids$matched <- 1
write.dta(matched.ids, file="matched.ids.dta")
recode$matched <- 0
recode$matched[recode$lga_id %in% matched.ids$lga_id == TRUE] <- 1
matched <- recode[recode$matched==1,]
write.dta(matched, file="matched.dta")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment