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

R中单因素logistic回归GLM模型批量提取系数和p值循环报错解决

问题原因
  • 你使用c(model1, model2...model7)拼接模型对象时,R会将多个模型的底层元素展开为原子向量,不会保留每个独立的完整模型结构,导致循环迭代的x不是glm模型对象,调用$运算符就会触发报错
  • 原有代码每次循环都会直接覆盖coeffs和p_values,最终只会保留最后一个模型的结果,没有实现追加存储的逻辑
正确实现代码

循环写法

coeffs <- c()
p_values <- c()
# 用list()存储所有模型,保留每个模型的完整结构
model_list <- list(model1, model2, model3, model4, model5, model6, model7)

for (x in model_list) {
  # 提取当前模型的系数和p值,追加到对应向量
  coeffs <- c(coeffs, summary(x)$coefficients[2, 1])
  p_values <- c(p_values, summary(x)$coefficients[2, 4])
}

# 可选:给向量添加对应模型的名称
names(coeffs) <- paste0("model", 1:7)
names(p_values) <- paste0("model", 1:7)

更简洁的向量化写法(可选)

不需要显式写循环,用sapply批量提取结果,代码更简洁:

model_list <- list(model1, model2, model3, model4, model5, model6, model7)
# 批量提取系数
coeffs <- sapply(model_list, function(m) summary(m)$coefficients[2,1])
# 批量提取p值
p_values <- sapply(model_list, function(m) summary(m)$coefficients[2,4])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 18:06:03