# NOT RUN {
##Example 1: identity link and no interaction
n <- 1000
psi <- 0.5
U <- rnorm(n) #confounder for X and Y
L <- rnorm(n) #confounder for Z and Y
Z <- rnorm(n) #instrument
X <- rnorm(n, mean=Z+L+U) #exposure
Y <- rnorm(n, mean=psi*X+L+U) #outcome
data <- data.frame(L, Z, X, Y)
fitX <- glm(X~Z+L, data=data)
fitY <- glm(Y~X+L, data=data)
fitIV <- tsls(fitX=fitX, fitY=fitY, data=data)
summary(fitIV)
##Example 2: logistic link and interaction between X and L
n <- 1000
psi0 <- 1
psi1 <- 0.5
U <- rnorm(n) #confounder for X and Y
L <- rnorm(n) #confounder for Z and Y
Z <- rnorm(n) #instrument
X <- rnorm(n, mean=Z+L+U) #exposure
Y <- rbinom(n, 1, plogis(psi0*X+psi1*X*L+L+U)) #outcome
data <- data.frame(L, Z, X, Y)
fitX <- glm(X~Z+L, data=data)
fitY <- glm(Y~X+L+X*L, data=data, family="binomial")
fitIV <- tsls(fitX=fitX, fitY=fitY, data=data, control=TRUE)
summary(fitIV)
# }
Run the code above in your browser using DataLab