如何从线性回归模型的摘要中提取系数值?
前两个可以通过 lm1$coefficients[1] 或 [2] 获得,但我不确定如何获得第三个值。在下面的 sprintf 代码中,如果使用 lm1$coefficients[3],我会得到 NA;如果使用 lm1$coefficients[1:2,1],则会得到不正确的维数。在摘要示例中,我想要替换 %s 的两个值是 295.274 和 62.012。有谁知道如何访问后者?
sprintf("The linear relationship can be described using the fitted regression line: Household debt = %s + %s", lm1$coefficients[1], lm1$coefficients[0,1])
> str(summary(M.lm)) # Truncated output...
List of 11
$ call : language lm(formula = MaxSalary ~ Score, data = salarygov)
$ terms :Classes 'terms', 'formula' length 3 MaxSalary ~ Score
...
$ residuals : Named num [1:495] -232.3 -132.6 37.9 114.3 232.3 ...
$ coefficients : num [1:2, 1:4] 295.274 5.76 62.012 0.123 4.762 ...
$ aliased : Named logi [1:2] FALSE FALSE
$ sigma : num 507
$ df : int [1:3] 2 493 2
$ r.squared : num 0.817
$ adj.r.squared: num 0.816
$ fstatistic : Named num [1:3] 2194 1 493
$ cov.unscaled : num [1:2, 1:2] 1.50e-02 -2.76e-05 -2.76e-05 5.88e-08
假设
fm <- lm(mpg ~ ., mtcars)
那么
coef(fm)
是系数向量,所以 coef(fm)[i]
是第 i 个系数。
如果由于某种原因你想使用summary的输出而不是lm的输出
s <- summary(fm)
那么
coef(s)[, 1]
是系数向量,所以 coef(s)[i, 1]
是第 i 个系数。
我们可以交替使用 coef(s)[i, "Estimate"] 因为
coef(s)
会产生一个带有名称的矩阵。