我是R的新手,习惯了非常基本的应用程序。 现在我遇到了一个需要帮助的问题:
我正在为有序逻辑回归寻找聚类标准错误的方法(我的估算类似于this示例)
我已经尝试 robcov 和 vcovCL ,他们给了我类似的错误消息:
非常感谢提前!
编辑: 我发现了一些关于缺失值的更多信息,但这似乎不是问题 - 因为即使我使用this回答解决问题,或者使用没有NA的数据集,它仍然存在。就像下面的例子一样。问题似乎是polr没有给出残差作为输出的一部分。我该如何解决这个问题?
dat <- read.dta("https://stats.idre.ucla.edu/stat/data/ologit.dta")
length(dat$apply)
twenty <- seq(from=1, to=20, by=1)
dat$clustervar<-sample(twenty, size=400, replace=TRUE)
m <- polr(apply ~ pared + public + gpa, data = dat, Hess=TRUE)
vcovCL <- function(x, cluster.by, type="sss", dfcw=1){
# R-codes (www.r-project.org) for computing
# clustered-standard errors. Mahmood Arai, Jan 26, 2008.
# The arguments of the function are:
# fitted model, cluster1 and cluster2
# You need to install libraries `sandwich' and `lmtest'
# reweighting the var-cov matrix for the within model
require(sandwich)
cluster <- cluster.by
M <- length(unique(cluster))
N <- length(cluster)
stopifnot(N == length(x$residuals))
K <- x$rank
##only Stata small-sample correction supported right now
##see plm >= 1.5-4
stopifnot(type=="sss")
if(type=="sss"){
dfc <- (M/(M-1))*((N-1)/(N-K))
}
uj <- apply(estfun(x), 2, function(y) tapply(y, cluster, sum))
mycov <- dfc * sandwich(x, meat=crossprod(uj)/N) * dfcw
return(mycov)
}
vcovCL(dat, m, dat$clustervar)
这给了我:
Error: N == length(x$residuals) is not TRUE
Called from: vcovCL(dat, m, dat$clustervar)
答案 0 :(得分:1)
我在“sandwich :: vcovCL”的帮助页面上取得了成功,它显示该函数的第一个arg是一个模型对象。需要使用::
运算符来屏蔽您提供的功能:
m <- polr(apply ~ pared + public + gpa, data = dat, Hess=TRUE)
( clval <- sandwich::vcovCL(m, dat$clustervar) )
pared public gpa unlikely|somewhat likely
pared 0.085218306 0.005588259 0.04584255 0.15545404
public 0.005588259 0.092283173 -0.01890725 -0.05875859
gpa 0.045842552 -0.018907254 0.07067573 0.22455931
unlikely|somewhat likely 0.155454041 -0.058758588 0.22455931 0.72408670
somewhat likely|very likely 0.165079639 -0.058282514 0.23631756 0.75713049
somewhat likely|very likely
pared 0.16507964
public -0.05828251
gpa 0.23631756
unlikely|somewhat likely 0.75713049
somewhat likely|very likely 0.80749182
如果您想要Wald测试,则可能需要使用该矩阵的diag
。我认为这就是coeftest将提供的:
coeftest( m, vcov = clval)
t test of coefficients:
Estimate Std. Error t value Pr(>|t|)
pared 1.047690 0.291922 3.5889 0.0003738 ***
public -0.058786 0.303781 -0.1935 0.8466565
gpa 0.615941 0.265849 2.3169 0.0210210 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
促使成功搜索Rhelp并找到Achim Zeileis答案的另一个问题是here