You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中为数据集各表型列循环执行多变量逻辑回归

问题描述

我有一个包含100例患者(示例展示7例)、2个协变量和50个表型(示例展示5个)的数据集,需要以Covariate1和Covariate2为协变量,针对每个表型执行多变量logistic回归来预测Outcome,最终要生成包含每个协变量的p值、OR值及置信区间(CI)的汇总表格。

我尝试了以下代码,但运行有问题:

for (i in df) {
  print(i)
  model <-glm(Outcome~ x[i] +Covariate1 +Covariate2, family = binomial(link = "logit"), data=df) 

参考过相关解决方案,但因变量与自变量顺序不符无法适用,特寻求帮助。

示例数据集:

df<-structure(list(ID = c(1, 2, 3, 4, 5, 6, 7), Outcome = c(0, 0, 
1, 1, 0, 1, 0), Covariate1 = c(1, 2, 3, 4, 5, 6, 7), Covariate2 = c(0, 
0, 0, 1, 1, 1, 1), P1 = c(1, 0, 0, 1, 1, 1, 2), P2 = c(0, 2, 
0, 1, 1, 1, 1), P3 = c(0, 0, 0, 1, 1, 1, 1), P4 = c(0, 0, 0, 
1, 2, 1, 1), P5 = c(0, 0, 0, 1, 1, 1, 2)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -7L))
解决方案

1. 筛选目标表型列

首先提取所有表型列名(示例中为P1到P5),避免循环到无关列:

# 获取以P开头的表型列名
pheno_cols <- grep("^P", colnames(df), value = TRUE)

2. 循环拟合模型并提取结果

遍历每个表型,动态构建回归公式,拟合模型后提取所需统计量:

# 初始化空列表存储结果
results_list <- list()

for (pheno in pheno_cols) {
  # 动态构建回归公式
  formula <- as.formula(paste("Outcome ~", pheno, "+ Covariate1 + Covariate2"))
  
  # 拟合logistic回归模型
  model <- glm(formula, family = binomial(link = "logit"), data = df)
  
  # 提取系数的统计信息
  coef_summary <- summary(model)$coefficients
  
  # 计算OR值和95%置信区间
  or_vals <- exp(coef(model))
  ci_vals <- exp(confint(model))
  
  # 整理当前表型的结果(剔除截距项)
  result_row <- data.frame(
    Phenotype = pheno,
    Variable = rownames(coef_summary)[-1],
    OR = round(or_vals[-1], 3),
    CI_Lower = round(ci_vals[-1, 1], 3),
    CI_Upper = round(ci_vals[-1, 2], 3),
    P_Value = round(coef_summary[-1, 4], 4)
  )
  
  results_list[[pheno]] <- result_row
}

# 合并所有结果为一个数据框
final_results <- do.call(rbind, results_list)

3. 查看最终输出

运行代码后,final_results即为汇总表格,示例输出片段:

print(final_results)
#   Phenotype    Variable    OR CI_Lower CI_Upper P_Value
# 1        P1          P1 1.000    0.018   55.971   1.000
# 2        P1  Covariate1 1.000    0.100   10.000   1.000
# 3        P1  Covariate2 7.000    0.046  1069.507   0.303
# ...(其余表型结果省略)

关键修正点

  • 原代码循环对象错误:for (i in df)遍历的是列值而非列名,改为遍历表型列名
  • 公式构建错误:使用as.formula()动态拼接公式,确保每个表型正确纳入模型
  • 剔除了无关的截距项结果,只保留表型和协变量的统计量

内容的提问来源于stack exchange,提问作者Carolin V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:00:45