Skip to content

Instantly share code, notes, and snippets.

@tslumley
Created October 21, 2020 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tslumley/b256c7bd93b1732d0bbd6c02984ebeae to your computer and use it in GitHub Desktop.
Save tslumley/b256c7bd93b1732d0bbd6c02984ebeae to your computer and use it in GitHub Desktop.
Chisquared goodness of fit test
svygofchisq<-function(formula, p, design,...){
means<-svytotal(formula, design,...)
rval<-chisq.test(means,p=p)
nm<-names(coef(means))
ncat<-length(coef(means))
means<-svycontrast(means, list(N=rep(1,ncat)), add=TRUE)
pN<-split(cbind(p,0*diag(p)), paste0("p_",nm))
names(pN)<-paste0("p_",nm)
means<-svycontrast(means, pN,add=TRUE)
for(i in 1:length(nm)){
O<-as.name(nm[i])
E<-as.name(names(pN)[i])
expr<-list(bquote((.(O)-.(E))^2/.(E)))
names(expr)[[1]]<-paste0("X2_",O)
means<-svycontrast(means,expr,add=TRUE)
}
result<-svycontrast(means, rep(c(1,0),c(ncat,2*ncat+1)))
rval$p.value<-pchisqsum(coef(result),rep(1,ncat), eigen(vcov(means)[1:ncat,1:ncat])$values)
rval$data.name<-deparse(formula)
rval$method<-"Design-based chi-squared test for given probabilities"
rval
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment