Skip to content

Instantly share code, notes, and snippets.

@tslumley
Created July 15, 2019 01:04
Show Gist options
  • Save tslumley/95b92d6a47a513787394d9d83a7c1f82 to your computer and use it in GitHub Desktop.
Save tslumley/95b92d6a47a513787394d9d83a7c1f82 to your computer and use it in GitHub Desktop.
survey-weighted two-stage least squares for instrumental variables
library(AER)
svyivreg<-function(formula, design, ...) UseMethod("svyivreg",design)
svyivreg.survey.design<-function(formula, design){
.data<-model.frame(design)
.data$.weights<-weights(design,"sampling")
model<- ivreg(formula, data=.data, weights=.weights)
U<-estfun(model)/weights(design,"sampling")
n<-NROW(U)
infl<- U%*%bread(model)/n
v<-vcov(svytotal(infl, design))
model$invinf<-model$cov.unscaled
model$cov.unscaled<-v
model$df.residual<-degf(design)+1-length(coef(model))
model$sigma<-model$sigma/sqrt(mean(weights(design,"sampling")))
model$call<-sys.call(-1)
class(model)<-"svyivreg"
model
}
print.svyivreg<-AER:::print.ivreg
summary.svyivreg<-function(object, df = NULL, ...){
AER:::summary.ivreg(object, vcov.=NULL, df=df, diagnostics=FALSE,...)
}
vcov.svyivreg<-function(object,...) object$cov.unscaled
svyivreg.svyrep.design<-function(formula, design,return.replicates=FALSE,...){
withReplicates(design, return.replicates=return.replicates,
function(.weights, .data){
.data$.pweights<-.weights
m<-ivreg(formula,data= .data, weights=.pweights)
coef(m)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment