Skip to content

Instantly share code, notes, and snippets.

@explodecomputer
Created April 12, 2016 06:41
Show Gist options
  • Save explodecomputer/8f939078d2d6257d54c100cf5cea1d5a to your computer and use it in GitHub Desktop.
Save explodecomputer/8f939078d2d6257d54c100cf5cea1d5a to your computer and use it in GitHub Desktop.
compare 2sls with 2 sample mr
library(TwoSampleMR)
library(systemfit)
# test 2sls
b <- matrix(rbinom(10000, 2, 0.5), 1000)
eff <- rnorm(10)
g <- b %*% eff * 100
u <- rnorm(1000)
x <- scale(rnorm(1000) + g - u) * 100
y <- scale(rnorm(1000) + 0.3 * x + u) * 100
dat <- data.frame(y, x, g, b)
i1 <- 1:500
i2 <- 501:1000
d1 <- dat[i1, ]
d2 <- dat[i2, ]
eff_hat <- array(0, 10)
eff_se <- array(0, 10)
for(i in 1:10)
{
mod <- summary(lm(d1$x ~ b[i1,i]))
eff_hat[i] <- mod$coefficients[2,1]
eff_se[i] <- mod$coefficients[2,2]
}
oeff_hat <- array(0, 10)
oeff_se <- array(0, 10)
for(i in 1:10)
{
mod <- summary(lm(d2$y ~ b[i2,i]))
oeff_hat[i] <- mod$coefficients[2,1]
oeff_se[i] <- mod$coefficients[2,2]
}
mr_ivw(eff_hat, oeff_hat, eff_se, oeff_se)
summary(systemfit(y ~ x, "2SLS", dat, inst = ~ X1 + X2 + X3 + X4 + X5 + X6 + X7 + X8 + X9 + X10))
summary(systemfit(y ~ x, "2SLS", dat, inst = ~ g))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment