编辑:我误会了你的问题。有两个方面:
一)na.omit
和na.exclude
两个做casewise缺失相对于这两个预测结果和准则。它们的不同之处仅在于,对于使用省略的情况,提取器函数像residuals()
或fitted()
将用NA
s 填充其输出na.exclude
,因此具有与输入变量相同长度的输出。
> N <- 20 # generate some data
> y1 <- rnorm(N, 175, 7) # criterion 1
> y2 <- rnorm(N, 30, 8) # criterion 2
> x <- 0.5*y1 - 0.3*y2 + rnorm(N, 0, 3) # predictor
> y1[c(1, 3, 5)] <- NA # some NA values
> y2[c(7, 9, 11)] <- NA # some other NA values
> Y <- cbind(y1, y2) # matrix for multivariate regression
> fitO <- lm(Y ~ x, na.action=na.omit) # fit with na.omit
> dim(residuals(fitO)) # use extractor function
[1] 14 2
> fitE <- lm(Y ~ x, na.action=na.exclude) # fit with na.exclude
> dim(residuals(fitE)) # use extractor function -> = N
[1] 20 2
> dim(fitE$residuals) # access residuals directly
[1] 14 2
b)真正的问题不在于na.omit
和之间的区别na.exclude
,您似乎不希望按条件删除,但同时考虑了标准变量。
> X <- model.matrix(fitE) # design matrix
> dim(X) # casewise deletion -> only 14 complete cases
[1] 14 2
回归结果取决于矩阵(设计矩阵伪逆,系数)和帽子矩阵,拟合值)。如果您不希望逐案删除,则需要为每一列使用不同的设计矩阵,因此无法为每个条件拟合单独的回归。您可以通过执行以下操作来尝试避免开销:X+= (X′X)− 1X′Xβ^= X+ÿH= XX+ÿ^= 高ÿXÿlm()
> Xf <- model.matrix(~ x) # full design matrix (all cases)
# function: manually calculate coefficients and fitted values for single criterion y
> getFit <- function(y) {
+ idx <- !is.na(y) # throw away NAs
+ Xsvd <- svd(Xf[idx , ]) # SVD decomposition of X
+ # get X+ but note: there might be better ways
+ Xplus <- tcrossprod(Xsvd$v %*% diag(Xsvd$d^(-2)) %*% t(Xsvd$v), Xf[idx, ])
+ list(coefs=(Xplus %*% y[idx]), yhat=(Xf[idx, ] %*% Xplus %*% y[idx]))
+ }
> res <- apply(Y, 2, getFit) # get fits for each column of Y
> res$y1$coefs
[,1]
(Intercept) 113.9398761
x 0.7601234
> res$y2$coefs
[,1]
(Intercept) 91.580505
x -0.805897
> coefficients(lm(y1 ~ x)) # compare with separate results from lm()
(Intercept) x
113.9398761 0.7601234
> coefficients(lm(y2 ~ x))
(Intercept) x
91.580505 -0.805897
请注意,在数值上可能会有更好的方法来计算和,您可以改为检查分解。此处在SE上解释了 SVD方法。对于实际使用,我尚未使用大型矩阵计时上述方法。X+HQ [Rÿlm()