rm(list = ls(all.names = TRUE)) install.packages("lmtest") install.packages("sandwich") install.packages("tidyverse") install.packages("boot") library("lmtest") library("sandwich") library("tidyverse") library(boot) #データを作成する set.seed(777) N <- 100000 id<- (1:100000) age <- floor(rnorm(N, 60, 10)) sex <- rbinom(N, 1, 0.5) ldl_base<-rnorm(N, 120+0.1*age-1.5*sex, 15) CHDhistory<-rbinom(N, 1, 1/(1+exp(-(-6+0.05*age-0.5*sex+0.01*ldl_base)))) statin_base<-rbinom(N, 1, 1/(1+exp(-(-5.6+0.05*age-0.5*sex+0.01*ldl_base+1*CHDhistory)))) ldl_follow<-rnorm(N, 120+0.1*age-30*sex+0.05*ldl_base+10*CHDhistory-20*statin_base, 15) statin_follow<-rbinom(N, 1, 1/(1+exp(-(-5+0.05*age-0.5*sex+2*statin_base+0.01*(ldl_base-100)+0.03*(ldl_follow-100)+0.2*CHDhistory)))) CHDevent<-rbinom(N, 1, 1/(1+exp(-(-12-0.2*statin_base-0.2*statin_follow-0.05*statin_base*statin_follow+0.1*age-0.5*sex+0.01*ldl_base+0.03*ldl_follow+1*CHDhistory)))) data<-data.frame(id, age, sex, ldl_base, ldl_follow, CHDhistory, statin_base, statin_follow, CHDevent) summary(data) #IPTW iptw<-function(d0, indices) { d <- d0[indices,] #T1に対する重みを求める psmodel1<-glm(statin_base ~ age+sex+ldl_base+CHDhistory, data=d, family=binomial(link="logit")) d$ps1<-predict(psmodel1, type = "response") psmodel2<-glm(statin_base ~ 1, data=d, family=binomial(link="logit")) d$ps2<-predict(psmodel2, type = "response") d$weight1 <- ifelse(d$statin_base==1, d$ps2/d$ps1, (1-d$ps2)/(1-d$ps1)) #d$weight1[d$weight1>quantile(d$weight1, c(.99))]<- quantile(d$weight1, c(.99)) #必要に応じてtruncateする #d$weight1[d$weight1quantile(d$weight2, c(.99))]<- quantile(d$weight2, c(.99)) #必要に応じてtruncateする #d$weight2[d$weight2