The code below currently runs unadjusted glm for each exposure on each outcome (3 exposures per outcome) and exports the results into a list. For each exposure, I need 3 models: model 1: unadjusted (which we currently have), model 2: adjusted for cov1, model 3: adjusted for cov1, cov2 and cov3
How would I implement the different models into this code?
amino_df <- data.frame(y = rbinom(100, 1, 0.5), y2 = rbinom(100, 1, 0.3), y3 = rbinom(100, 1, 0.2), y4 = rbinom(100, 1, 0.22),
exp1 = rnorm(100), exp2 = rnorm(100), exp3 = rnorm(100),
cov1 = rnorm(100), cov2 = rnorm(100), cov3 = rnorm(100))
exp <- c("exp1", "exp2", "exp3")
y <- c("y", "y2","y3","y4")
cov <- c("cov1", "cov2", "cov3")
obs_results <- replicate(length(y), data.frame())
for(j in seq_along(y)){
for (i in seq_along(exp)){
mod <- as.formula(paste(y[j], "~", exp[i]))
glmmodel <- glm(formula = mod, family = binomial, data = amino_df)
obs_results[[j]][i,1] <- names(coef(glmmodel))[2]
obs_results[[j]][i,2] <- exp(glmmodel$coefficients[2])
obs_results[[j]][i,3] <- summary(glmmodel)$coefficients[2,2]
obs_results[[j]][i,4] <- summary(glmmodel)$coefficients[2,4]
obs_results[[j]][i,5] <- exp(confint.default(glmmodel)[2,1])
obs_results[[j]][i,6] <- exp(confint.default(glmmodel)[2,2])
}
colnames(obs_results[[j]]) <- c("exposure","OR", "SE", "P_value", "95_CI_LOW","95_CI_HIGH")
}
names(obs_results) <- y
obs_df <- do.call("rbind", lapply(obs_results, as.data.frame))
EDIT - I now have a solution:
Further question, could this code below be adapted to include different models for the different exposures? So for exp1, adjust for all 3 cons: cov1, cov2, cov3, but for exp2 adjust for cov1, cov2 only? and exp3 cov2 and cov1 only?
amino_df <- data.frame(y = rbinom(100, 1, 0.5), y2 = rbinom(100, 1, 0.3),
y3 = rbinom(100, 1, 0.2), y4 = rbinom(100, 1, 0.22),
exp1 = rnorm(100), exp2 = rnorm(100), exp3 = rnorm(100),
cov1 = rnorm(100), cov2 = rnorm(100), cov3 = rnorm(100))
exp <- c("exp1", "exp2", "exp3")
y <- c("y", "y2","y3","y4")
model <- c("", "+ cov1", "+ cov1 + cov2 + cov3")
obs_df <- lapply(y, function(j){
lapply(exp, function(i){
lapply(model, function(h){
mod = as.formula(paste(j, "~", i, h))
glmmodel = glm(formula = mod, family = binomial, data = amino_df)
obs_results = data.frame(
outcome = j,
exposure = names(coef(glmmodel))[2],
covariate = h,
OR = exp(glmmodel$coefficients[2]),
SE = summary(glmmodel)$coefficients[2,2],
P_value = summary(glmmodel)$coefficients[2,4],
`95_CI_LOW` = exp(confint.default(glmmodel)[2,1]),
`95_CI_HIGH` = exp(confint.default(glmmodel)[2,2])
)
return(obs_results)
}) %>% bind_rows
}) %>% bind_rows
}) %>% bind_rows %>% `colnames<-`(gsub("X95","95",colnames(.))) %>% `rownames<-`(NULL)
head(obs_df)