如何在R中同时运行多个logistic回归模型并批量计算对应p值
R实现批量单因素Logistic回归及结果汇总
假设你的数据集存储为数据框对象dat,且第一列为二分类因变量,其余列为自变量,可直接运行以下代码:
# 依赖包安装(仅首次运行需要) # install.packages(c("broom", "dplyr")) library(broom) library(dplyr) # 提取自变量列名 iv_list <- colnames(dat)[-1] # 批量拟合模型并提取结果 logit_result <- lapply(iv_list, function(iv) { # 自动将二元自变量转为因子类型,可根据需求修改判定规则 if (length(unique(na.omit(dat[[iv]]))) == 2) { dat[[iv]] <- as.factor(dat[[iv]]) } # 拟合单因素logistic回归 model <- glm(reformulate(response = colnames(dat)[1], termlabels = iv), data = dat, family = binomial("logit")) # 提取OR、95%CI、p值,过滤截距项 model_res <- tidy(model, exponentiate = T, conf.int = T) %>% filter(term != "(Intercept)") %>% mutate(independent_var = iv) %>% select(independent_var, term, or = estimate, conf_low = conf.low, conf_high = conf.high, p_value = p.value) return(model_res) }) %>% bind_rows() # 输出汇总结果 View(logit_result)
补充说明
- 若你有明确的需要转因子的变量列表,可替换自动判定逻辑:将
if判断替换为if (iv %in% c("你指定的变量名1", "变量名2"))即可 - 若需要保留截距项的计算结果,删除
filter(term != "(Intercept)")行 - 最终输出的
logit_result为结构化数据框,可直接导出为csv等格式使用
内容的提问来源于stack exchange,提问作者Kai Jiang
相关产品推荐
相关产品推荐

