[英]looping through glm in R
我想创建一个脚本来自动执行多个 (n=45) 变量的 glm 函数。 目前我是单独执行的,这很乏味;
df1
ID status B01 B02 B03 B04 B05.......B045
01 0 0 1 1 0 0 0
02 1 1 0 0 0 1 0
03 1 1 1 0 0 0 0
04 0 0 0 0 0 1 1
05 0 1 0 0 0 0 1
ItB01 <- (glm(status ~ B01, data=df1, family = binomial(link = 'logit')))
#for tidy export
library(broom)
tidy_ItB01 <-tidy(ItB01)
tidy_ItB01
write.csv(tidy_ItB01, "ItB01_coef.csv")
#convert to OR and export
library(epiDisplay)
logistic.display(ItB01) -> table2
attributes(table2)
table2$table
ItB01 <- as.data.frame(table2$table)
write.csv(ItB01, file="ItB01_OR.csv")
我对变量 B02 到 B45 重复整个过程。 任何建议如何自动化该过程?
您可以将公式构建为字符串,然后使用循环:
library(broom)
library(epiDisplay)
vars = names(df1)[-(1:2)]
formula_strings = sprintf("status ~ %s", vars)
file_prefix = sprintf("It%s_", vars)
for (i in seq_along(vars)) {
mod = glm(as.formula(formula_strings[i]), data=df1, family = binomial(link = 'logit'))
coefs = tidy(mod)
write.csv(coefs, paste0(file_prefix[i], "coef.csv")
#convert to OR and export
OR = as.data.frame(logistic.display(mod)$table)
write.csv(OR, file = paste0(file_prefix[i], "OR.csv"))
}
您可能还想将中间结果保存在列表中。 如果是这样,请添加以下代码:
## before the loop, initialize empty lists
coefs = list()
odds_ratios = list()
## inside the loop, assign to the lists
coefs[[vars[i]]] = coefs
odds_ratios[[vars[i]]] = OR
## after the loop, access elements with [[
## e.g., coefs[["B04"]]
你可以像这样用mapply
做整个事情:
library(broom)
library(epiDisplay)
mapply(function(x, y) {
mod <- glm(df1$status ~ x, family = binomial(link = 'logit'))
write.csv(tidy(mod), paste0("It", y, "_coef.csv"))
write.csv(as.data.frame(logistic.display(mod)$table), paste0("It", y, "_OR.csv"))
}, df1[-(1:2)], names(df1[-(1:2)]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.