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
相关产品推荐
相关产品推荐

