我正在分析一个数据集,其中的数据被分成了几个组(地区内的城镇)。这个数据集看起来像:
R> df <- data.frame(x = rnorm(10),
y = 3*rnorm(x),
groups = factor(sample(c('0','1'), 10, TRUE)))
R> head(df)
x y groups
1 -0.8959 1.54 1
2 -0.1008 -2.73 1
3 0.4406 0.44 0
4 0.0683 1.62 1
5 -0.0037 -0.20 1
6 -0.8966 -2.34 0
我希望我的lm()估计能考虑到组内相关性,为此我使用了一个名为cl()
的函数,它接受一个lm()
并返回强健的聚类协方差矩阵(原始文献在这里):
cl <- function(fm, cluster) {
library(sandwich)
M <- length(unique(cluster))
N <- length(cluster)
K <- fm$rank
dfc <- (M/(M-1))*((N-1)/(N-K-1))
uj <- apply(estfun(fm), 2, function(x) tapply(x, cluster, sum));
vcovCL <- dfc * sandwich(fm, meat = crossprod(uj)/N)
return(vcovCL)
}
现在,
output <- lm(y ~ x, data = df)
clcov <- cl(output, df$groups)
coeftest(output, clcov, nrow(df) - 1)
给我所需的估计值。现在的问题是,我想要使用该模型进行预测,而我需要使用新协方差矩阵clcov
来计算预测的标准误差。
predict(output, se.fit = TRUE)
使用clcov
代替vcov(output)
。类似于vcov() <-
的东西将是完美的。当然,我可以编写自己的函数来进行预测,但我只是想知道是否有更实用的方法可以让我使用lm
签名的方法(例如arm::sim)。
glmm
模型。 - griverorz