# NOT RUN {
# Example 1
set.seed(2)
n <- 5000
## parameter a0 determines the outcome prevalence
a0 <- -4
psi.true <- 1
l <- rbinom(n, 1, 0.5)
u <- rbinom(n, 1, 0.5)
z <- rbinom(n, 1, plogis(a0))
x <- rbinom(n, 1, plogis(a0+3*z+ u))
y <- rbinom(n, 1, exp(a0+psi.true*x+u))
d <- data.frame(z,u,x,y,l)
## Outcome prevalence
mean(d$y)
####### G-estimation
## log CRR
fitz.l <- glm(z~1, family=binomial, data=d)
gest_log <- ivglm(estmethod="g", X="x", Y="y",
fitZ.L=fitz.l, data=d, link="log")
AFgestlog <- AFivglm(gest_log, data=d)
summary(AFgestlog)
## log COR
## Associational model, saturated
fit_y <- glm(y~x+z+x*z, family="binomial", data=d)
## Estimations of COR and AF
gest_logit <- ivglm(estmethod="g", X="x", Y="y",
fitZ.L=fitz.l, fitY.LZX=fit_y,
data=d, link="logit")
AFgestlogit <- AFivglm(gest_logit, data = d)
summary(AFgestlogit)
####### TS estimation
## log CRR
# First stage
fitx <- glm(x ~ z, family=binomial, data=d)
# Second stage
fity <- glm(y ~ x, family=poisson, data=d)
## Estimations of CRR and AF
TSlog <- ivglm(estmethod="ts", X="x", Y="y",
fitY.LX=fity, fitX.LZ=fitx, data=d, link="log")
AFtslog <- AFivglm(TSlog, data=d)
summary(AFtslog)
## log COR
# First stage
fitx_logit <- glm(x ~ z, family=binomial, data=d)
# Second stage
fity_logit <- glm(y ~ x, family=binomial, data=d)
## Estimations of COR and AF
TSlogit <- ivglm(estmethod="ts", X="x", Y="y",
fitY.LX=fity_logit, fitX.LZ=fitx_logit,
data=d, link="logit")
AFtslogit <- AFivglm(TSlogit, data=d)
summary(AFtslogit)
## Example 2: IV-outcome confounding by L
####### G-estimation
## log CRR
fitz.l <- glm(z~l, family=binomial, data=d)
gest_log <- ivglm(estmethod="g", X="x", Y="y",
fitZ.L=fitz.l, data=d, link="log")
AFgestlog <- AFivglm(gest_log, data=d)
summary(AFgestlog)
## log COR
## Associational model
fit_y <- glm(y~x+z+l+x*z+x*l+z*l, family="binomial", data=d)
## Estimations of COR and AF
gest_logit <- ivglm(estmethod="g", X="x", Y="y",
fitZ.L=fitz.l, fitY.LZX=fit_y,
data=d, link="logit")
AFgestlogit <- AFivglm(gest_logit, data = d)
summary(AFgestlogit)
####### TS estimation
## log CRR
# First stage
fitx <- glm(x ~ z+l, family=binomial, data=d)
# Second stage
fity <- glm(y ~ x+l, family=poisson, data=d)
## Estimations of CRR and AF
TSlog <- ivglm(estmethod="ts", X="x", Y="y",
fitY.LX=fity, fitX.LZ=fitx, data=d,
link="log")
AFtslog <- AFivglm(TSlog, data=d)
summary(AFtslog)
## log COR
# First stage
fitx_logit <- glm(x ~ z+l, family=binomial, data=d)
# Second stage
fity_logit <- glm(y ~ x+l, family=binomial, data=d)
## Estimations of COR and AF
TSlogit <- ivglm(estmethod="ts", X="x", Y="y",
fitY.LX=fity_logit, fitX.LZ=fitx_logit,
data=d, link="logit")
AFtslogit <- AFivglm(TSlogit, data=d)
summary(AFtslogit)
# }
Run the code above in your browser using DataLab