如何从Type II平方和的线性回归模型输出中提取斜率、截距和R²?
提取线性回归的斜率、截距与R²(Type II平方和分析场景)
首先要明确:car::Anova(model, type="II")输出的是Type II平方和的方差分析结果,仅用于检验自变量的显著性;而斜率、截距、R²这些是线性回归模型本身的拟合参数与指标,直接从你拟合的lm对象里提取即可,和Type II平方和的分析步骤完全不冲突。
提取截距和斜率
用coef()函数直接从model对象中提取系数:
# 提取模型系数(包含截距和x的斜率) model_coefs <- coef(model) intercept <- model_coefs[1] # 截距项 slope <- model_coefs[2] # 自变量x的斜率 # 打印结果 cat("截距:", intercept, "\n") cat("斜率:", slope, "\n")
提取R²
从模型的摘要结果中提取R²,或者直接调用对应的属性:
# 生成模型摘要并提取R² model_summary <- summary(model) r_squared <- model_summary$r.squared # 打印结果 cat("R²:", r_squared, "\n")
完整示例代码
把所有步骤整合后的可运行代码:
df <- data.frame(x = c(1, 2, 3, 4, 5), y = c(2, 4, 6, 8, 10.5)) model <- lm(y ~ x, data = df) anova_result <- car::Anova(model, type="II") # 提取截距、斜率 model_coefs <- coef(model) intercept <- model_coefs[1] slope <- model_coefs[2] # 提取R² r_squared <- summary(model)$r.squared # 输出所有结果 cat("=== 模型拟合参数 ===\n") cat("截距:", round(intercept, 3), "\n") cat("斜率:", round(slope, 3), "\n") cat("R²:", round(r_squared, 3), "\n") cat("\n=== Type II平方和方差分析结果 ===\n") print(anova_result)
补充说明
- Type II平方和分析聚焦于自变量效应的显著性检验,而截距、斜率是模型的具体参数取值,R²是模型的拟合优度指标,二者属于不同维度的结果。
- 如果需要调整后的R²,可提取
model_summary$adj.r.squared。
内容的提问来源于stack exchange,提问作者Yujie Liu
相关产品推荐
相关产品推荐

