ggplot2中的鲁棒标准误差

3

我想使用ggplot2绘制模型。我已经估计了一个鲁棒的方差协方差矩阵,希望在估计置信区间时使用。

我能否告诉ggplot2使用我的VCOV,或者,是否可以通过某种方式强制predict.lm使用我的VCOV矩阵?一个虚拟的例子:

source("http://people.su.se/~ma/clmclx.R")
df <- data.frame(x1 = rnorm(100), x2 = rnorm(100), y = rnorm(100), group = as.factor(sample(1:10, 100, replace=T))) 
lm1 <- lm(y ~ x1 + x2, data = df)
coeftest(lm1)
## outputs coef.test, but can be modified to output VCOV
clx(lm1, 1, df$group)

如果我能够得到基于增广VCOV矩阵的“正确”预测结果,那么将其添加到ggplot中就相对容易。
1个回答

4
只有标准误差会改变,而预测值不会改变,是吗?
getvcov <- function(fm,dfcw,cluster) {
  library(sandwich);library(lmtest)
  M <- length(unique(cluster))   
  N <- length(cluster)           
  K <- fm$rank                        
  dfc <- (M/(M-1))*((N-1)/(N-K))  
  uj  <- apply(estfun(fm),2, function(x) tapply(x, cluster, sum));
  dfc*sandwich(fm, meat=crossprod(uj)/N)*dfcw
}

V <- getvcov(lm1,1,df$group)
X <- as.matrix(model.frame(lm1))
se <- predict(lm1,se=TRUE)$se.fit
se_robust <- sqrt(diag(X %*% V %*% t(X)))

这太棒了。谢谢Ben。核心R函数非常强大,但我经常发现自己不够熟悉它们,无法充分利用它们的潜力。 - Rasmus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接