##################
# example single run of a 2-stage G-dWOLS analysis
set.seed(1)
# number of stages
k<-2
# number of bins for categorized weight functions
m<-5
# sample size
n<-1000
# parameter values
psi.mat<-matrix(rep(c(1,1,-1),2),byrow=TRUE,nrow=2)
alpha.mat<-matrix(rep(c(-1,1),2),byrow=TRUE,nrow=2)
### generate data
# stage 1
x1<-abs(rnorm(n,10,1))
a1<-rnorm(n,alpha.mat[1,1]+alpha.mat[1,2]*x1,1)
# stage 2
x2<-abs(rnorm(n,10,1))
a2<-rnorm(n,alpha.mat[2,1]+alpha.mat[2,2]*x2,1)
# blips
gamma1<-as.matrix(cbind(a1,a1*x1,a1^2))
gamma2<-as.matrix(cbind(a2,a2*x2,a2^2))
# y: outcome
# y <- trmt free + blip
y<-log(x1)+sin(x1)+log(x2)+sin(x2)+gamma1+gamma2 + rnorm(n,0,1)
# convert to a vector for formatting into data frame
y <- as.vector(y)
# data
data<-data.frame(cbind(y,x1,x2,a1,a2))
# models to be passed to gdwols function
# tailoring variables that interact with a1
Xpsi1<-list(~x1,~x2)
# tailoring variables that interact with a2
Xpsi2<-list(~1,~1)
# treatment model at each stage
treat.mod<-list(a1~x1,a2~x2)
# treatment-free model at each stage (misspecified)
tf.mod<-list(~x1,~log(x2)+sin(x2))
out1 <- gdwols(y, Xpsi1, Xpsi2, treat.mod, treat.fam = gaussian(link = "identity"),
tf.mod, weight.fcn="ipw", data, m, k)
out1$psi
out2 <- gdwols(y, Xpsi1, Xpsi2, treat.mod, treat.fam = gaussian(link = "identity"),
tf.mod, weight.fcn="cipw", data, m, k)
out2$psi
out3 <- gdwols(y, Xpsi1, Xpsi2, treat.mod, treat.fam = gaussian(link = "identity"),
tf.mod, weight.fcn="qpom", data, m, k)
out3$psi
out4 <- gdwols(y, Xpsi1, Xpsi2, treat.mod, treat.fam = gaussian(link = "identity"),
tf.mod, weight.fcn="wo", data, m, k)
out4$psi
##################
Run the code above in your browser using DataLab