gpt4 book ai didi

r - 如何从 r 中的回归摘要中仅返回自由度?

转载 作者:行者123 更新时间:2023-12-01 16:57:14 25 4
gpt4 key购买 nike

我只想从摘要中返回 df(自由度)。我通过互联网进行了搜索,但没有找到任何相关内容。

    y=c(2,13,0.4,5,8,10,13)
y1=c(2,13,0.004,5,8,1,13)
y2=c(2,3,0.004,15,8,10,1)
y3=c(2,2,2,2,2,2,NA)
fit=lm(y~y1+y2+y3)
summary(fit)
Call:
lm(formula = y ~ y1 + y2 + y3)

Residuals:
1 2 3 4 5 6
-1.5573 1.6523 -1.3718 -3.2909 -0.9247 5.4924

Coefficients: (1 not defined because of singularities)
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.7682 3.0784 0.574 0.606
y1 0.6896 0.3649 1.890 0.155
y2 0.2050 0.3184 0.644 0.566
y3 NA NA NA NA

Residual standard error: 4.037 on 3 degrees of freedom
(1 observation deleted due to missingness)
Multiple R-squared: 0.58, Adjusted R-squared: 0.3
F-statistic: 2.071 on 2 and 3 DF, p-value: 0.2722

有没有只返回 df 的函数示例

         df(fit) or fit$df
3

最佳答案

在评论中,OP提到他们使用的是lm.fit()而不是lm(),因此演示如何执行此操作的示例代码是完全不同的; lm.fit() 需要用户提供矢量响应和正确的模型矩阵,lm() 会为您完成所有这些工作。因此,x3NA 的存在是我们需要考虑的一个问题,无论如何,df.residual() 也适用于该示例:

Xy <- cbind(y  = c(2,13,0.4,5,8,10,13),
x0 = rep(1, 7),
x1 = c(2,13,0.004,5,8,1,13),
x2 = c(2,3,0.004,15,8,10,1),
x3 = c(2,2,2,2,2,2,NA))
Xy <- Xy[complete.cases(Xy), ]
X <- Xy[, -1]
y <- Xy[, 1]

fit <- lm.fit(X, y)

R> df.residual(fit)
[1] 3
<小时/>

检查拟合对象拟合

Xy <- data.frame(y = c(2,13,0.4,5,8,10,13),
x1 = c(2,13,0.004,5,8,1,13),
x2 = c(2,3,0.004,15,8,10,1),
x3 = c(2,2,2,2,2,2,NA))
fit <- lm(y ~ x1 + x2 + x3, data = Xy)

str(fit, max = 1)

R> str(fit, max = 1)
List of 13
$ coefficients : Named num [1:4] 1.768 0.69 0.205 NA
..- attr(*, "names")= chr [1:4] "(Intercept)" "x1" "x2" "x3"
$ residuals : Named num [1:6] -1.557 1.652 -1.372 -3.291 -0.925 ...
..- attr(*, "names")= chr [1:6] "1" "2" "3" "4" ...
$ effects : Named num [1:6] -15.68 -7.79 2.6 -3.22 -0.98 ...
..- attr(*, "names")= chr [1:6] "(Intercept)" "x1" "x2" "" ...
$ rank : int 3
$ fitted.values: Named num [1:6] 3.56 11.35 1.77 8.29 8.92 ...
..- attr(*, "names")= chr [1:6] "1" "2" "3" "4" ...
$ assign : int [1:4] 0 1 2 3
$ qr :List of 5
..- attr(*, "class")= chr "qr"
$ df.residual : int 3
$ na.action :Class 'omit' Named int 7
.. ..- attr(*, "names")= chr "7"
$ xlevels : Named list()
$ call : language lm(formula = y ~ x1 + x2 + x3, data = Xy)
$ terms :Classes 'terms', 'formula' length 3 y ~ x1 + x2 + x3
.... <removed>
$ model :'data.frame': 6 obs. of 4 variables:
.... <removed>
- attr(*, "class")= chr "lm"

您将在此处注意到 df.residual 组件。您可以像从列表中提取任何其他对象一样提取

R> fit$df.residual
[1] 3

但这会错过提取器函数df.residual(),它会为您完成所有工作

R> df.residual(fit)
[1] 3

这样做的好处是,函数编写者应该关心,他们可以在他们的包中包含一个 df.residual() 方法,这样这也适用于他们的模型类,而你只需记住一个函数名称...

关于r - 如何从 r 中的回归摘要中仅返回自由度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21734248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com