在評論暗示了任何功能,OP提到他們使用lm.fit()
而不是lm()
因此示例代碼演示如何做到這一點是非常不同的; lm.fit()
需要矢量響應和由用戶提供的正確模型矩陣,lm()
可以爲您做所有這些。因此的NA
在的存在是我們需要考慮的,反正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
檢查裝配對象fit
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()
的方法,所以這也適用於他們的類型模型,而您只需要記住一個單一的函數名稱......
'適合$ df.residual'? – Justin
使用你的例子,'fit $ df.residual'返回'3' ... FWIW,你可以使用'fit $'+ tab或者'str(fit)'來查看你的擬合物體附着的東西。 – Justin