2012-02-13 28 views
3

我想用ggplot2绘制一个模型。我估计了一个稳健的方差 - 协方差矩阵,我想在估计置信区间时使用它。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) 

这将是比较容易添加到ggplot,如果我能得到给我的增强VCOV矩阵“正确”的预测。

回答

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))) 
+0

这是真棒。谢谢Ben。核心R功能非常棒,功能强大,但我经常发现自己无法充分发挥它们的潜力。 – Rasmus 2012-02-13 18:09:45