本章介绍倾向性评分匹配(PSM)
#第4章 倾向性评分匹配PSM ####
#用MatchIt包做PSM
install.packages("MatchIt")
library(MatchIt)
lalonde <- read.dta("D:/BaiduNetdiskDownload/lalonde.dta")
#数据集lalonde变量解释:treat是分组变量,age年龄,educ教育程度,black人种,hispan是否是西班牙人
#married是否已婚,nodegree是否有学位,re74和re75基础工资,re78结局变量
head(lalonde)
f <- matchit(treat ~ age + educ + black + hispan +
married + nodegree + re74 + re75,data = lalonde,method = "nearest")
summary(f)
f1 <- matchit(treat ~ age + educ + black + hispan + married + nodegree +
re74 + re75,data = lalonde,method = "nearest",caliper = 0.05)
summary(f1)
matchdata <- match.data(f)
matchdata
install.packages("writexl")
library(writexl)
matchdata$id <- 1:nrow(matchdata)
write_xlsx(matchdata,path = "D:/Downloadings__Transit/matchdata.xlsx")
#用nonrandom包做PSM
install.packages("devtools")
devtools::install_github("cran/nonrandom")
#nonrandom包需要从github上下载
install.packages("nonrandom")
library(nonrandom)
data(stu1)
View(stu1)
stu1.ps <- pscore(data=stu1,formula = therapie ~ tgr + age)
stu1.match <- ps.match(object = stu1.ps,ratio = 2,caliper = 0.05,givenTmatchingC = FALSE,
matched.by = "pscore",setseed = 38902,combine.output = TRUE)
matchdata <- stu1.match$data.matched
matchdata
plot.pscore(x=stu1.ps,main = "PS disturibtion",xlab = "",par.1 = list(col="red"),
par.0 = list(lwd=2),par.dens = list(kernel = "gaussian"))