-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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