エラーを再現するために、おもちゃの例を含めました。
data(cars)
cars$dist[cars$dist<5]<-NA
cars$fast<- (cars$speed>10)*1
fit<-lm(speed~dist,cars)
cl <- function(dat,fm, cluster){
require(sandwich, quietly = TRUE)
require(lmtest, quietly = TRUE)
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));
vcovCL <- dfc*sandwich(fm, meat=crossprod(uj)/N)
result<-coeftest(fm, vcovCL)
return(result)}
cl(cars,fit,cars$fast)
Error in tapply(x, cluster, sum) : arguments must have same length
問題は、削除された NA とサブセット回帰により、元のデータフレームが回帰で使用されるデータフレームよりも大きいことです。堅牢な標準誤差を計算する必要があるため、関数 cl を使用して SE を計算する必要がありますが、削除された NA を特定して適切にサブセット化し、データフレームに適したクラスターを特定するにはどうすればよいでしょうか。
前もって感謝します。