2012-02-13 24 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