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

在R语言中如何从线性回归模型的summary结果中提取指定系数相关数值?

在R语言中如何从线性回归模型的summary结果中提取指定系数相关数值?

嗨,我来帮你理清这个问题~

首先得搞清楚两个核心对象的区别:

  • 你直接用lm1$coefficients调用的是原始线性回归模型对象里的系数,它只是一个一维向量,只包含截距和自变量的系数估计值——所以你用[3]会得到NA(总共只有2个值),用二维索引[1:2,1]会报错(向量没有列维度)。
  • 而summary(lm1)返回的是一个汇总对象,里面的coefficients是一个矩阵,包含了4列:系数估计值(Estimate)、标准误(Std. Error)、t值(t value)、p值(Pr(>|t|)),行则对应各个系数(截距(Intercept)和你的自变量Score)。

你想要的295.274是截距的系数估计值,62.012是截距的标准误,正确的提取方式如下:

步骤1:先存储summary结果

为了后续操作更清晰,建议先把汇总结果存成单独的对象:

# 先拟合你的回归模型
lm1 <- lm(MaxSalary ~ Score, data = salarygov)
# 存储模型的汇总结果
lm1_summary <- summary(lm1)

步骤2:提取目标数值

你可以用位置索引,也可以用更直观的行名列名来提取(后者更不容易出错):

  • 提取截距的估计值(295.274):
    # 位置索引:第1行第1列
    lm1_summary$coefficients[1, 1]
    # 行名列名索引(可读性更强)
    lm1_summary$coefficients["(Intercept)", "Estimate"]
    
  • 提取截距的标准误(62.012):
    # 位置索引:第1行第2列
    lm1_summary$coefficients[1, 2]
    # 行名列名索引
    lm1_summary$coefficients["(Intercept)", "Std. Error"]
    
  • 如果要提取自变量Score的系数估计值(也就是你例子里的5.76):
    lm1_summary$coefficients[2, 1]
    # 或者行名列名
    lm1_summary$coefficients["Score", "Estimate"]
    

修正你的sprintf代码

把你的代码改成用summary对象里的矩阵取值,就不会再出现NA或者维度错误了:

sprintf("The linear relationship can be described using the fitted regression line: Household debt = %s + %s*Score", 
        lm1_summary$coefficients["(Intercept)", "Estimate"], 
        lm1_summary$coefficients["Score", "Estimate"])

如果还想把截距的标准误也补充进去,可以这样写:

sprintf("The linear relationship can be described using the fitted regression line: Household debt = %s (%s) + %s*Score", 
        lm1_summary$coefficients["(Intercept)", "Estimate"],
        lm1_summary$coefficients["(Intercept)", "Std. Error"],
        lm1_summary$coefficients["Score", "Estimate"])

备注:内容来源于stack exchange,提问作者Crimson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 10:40:28