Last active
March 7, 2023 21:00
-
-
Save mikelove/3e1817b34df294011ceb01e24059a365 to your computer and use it in GitHub Desktop.
Bivariate MR simulation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(tidyr) | |
library(purrr) | |
library(broom) | |
library(tibble) | |
n <- 1000 | |
dat <- matrix(runif(6*n),nrow=n) | |
colnames(dat) <- paste0("parent", rep(c("x","y"),c(3,3)), c(1:3,1:3)) | |
dat <- as_tibble(dat) | |
myscale <- function(x) x / sd(x) | |
coin <- TRUE | |
if (coin) { | |
dat <- dat %>% | |
mutate(x = myscale(1 * parentx1 + 2 * parentx2 + 3 * parentx3 + rnorm(n,0,2)), | |
y = myscale(1 * parenty1 + 2 * parenty2 + 3 * parenty3 + x + rnorm(n))) | |
} else { | |
dat <- dat %>% | |
mutate(y = myscale(1 * parenty1 + 2 * parenty2 + 3 * parenty3 + rnorm(n,0,2)), | |
x = myscale(1 * parentx1 + 2 * parentx2 + 3 * parentx3 + y + rnorm(n))) | |
} | |
tidy_named_coef <- function(x,suffix) { | |
setNames(tidy(x)[,1:3], | |
paste0(c("term","est","se"),suffix)) | |
} | |
dat %>% | |
pivot_longer(cols=starts_with("parent"), names_to="variable", values_to="independent") %>% | |
nest(.by = variable) %>% | |
mutate(x_model = map(data, ~ lm(x ~ independent, data=.)), | |
y_model = map(data, ~ lm(y ~ independent, data=.))) %>% | |
mutate(x_coef = map(x_model, tidy_named_coef, "_x"), | |
y_coef = map(y_model, tidy_named_coef, "_y")) %>% | |
unnest(cols=c(x_coef, y_coef)) %>% | |
filter(term_x == "independent") %>% | |
select(variable, starts_with(c("est","se"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment