Skip to content

Instantly share code, notes, and snippets.

@tslumley
Created August 21, 2014 23:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tslumley/7a8e7f64c2a2b56aec04 to your computer and use it in GitHub Desktop.
Save tslumley/7a8e7f64c2a2b56aec04 to your computer and use it in GitHub Desktop.
Margin of error in polls, based on actual percentage and allowing for design effects
moe = function(pct, N=1000, deff=c(1,2)){
p.L = function(x, n) {
ifelse (x == 0,0,qbeta(0.025, x, n - x + 1))
}
p.U = function(x, n) {
ifelse(x == n,1,qbeta(0.975, x + 1, n - x))
}
N = rep(N,length(pct))
lower = function(pct,deff){
n = outer(N,deff,"/")
x = n*pct/100
round(100*p.L(x,n),1)
}
upper = function(pct,deff){
n = outer(N,deff,"/")
x = n*pct/100
round(100*p.U(x,n),1)
}
l = lower(pct,deff)
u = upper(pct,deff)
rval =list()
for (i in 1:length(deff)){
rval[[i]] = cbind(l=l[,i],u=u[,i])
rownames(rval[[i]])=pct
}
names(rval)=paste("Design.effect",deff,"=")
rval
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment