Skip to content

Instantly share code, notes, and snippets.

@peterdalle
Created July 13, 2017 19:59
Show Gist options
  • Save peterdalle/215470af0d7d65102255027923c9963e to your computer and use it in GitHub Desktop.
Save peterdalle/215470af0d7d65102255027923c9963e to your computer and use it in GitHub Desktop.
Calculate margin of error from proportion, and return confidence interval
# Calculate margin of error from proportion, and return confidence interval.
# p = proportion (0-1)
# n = total sample size
# z = z score (defaults to 1.96 = 95 % confidence interval)
# digits = number of decimal places to be used (defaults to 2)
moe <- function(p, n, z=1.96, digits=2) {
if(p > 1) { stop("p must be a proportion. For example, for 30 % use p = 0.30") }
error <- z * (sqrt(p * (1 - p) / n)) * 100 # Calculate margin of error.
conf.level <- round(100 - (pnorm(z, lower.tail=FALSE) * 2) * 100, 0) # Convert z to confidence level (two-tailed).
conf.lower <- p * 100 - error # Confidence interval lower bound.
conf.upper <- p * 100 + error # Confidence interval upper bound.
return(paste("Proportion: ", p * 100, " % (", # Nicely formatted message.
conf.level, " % CI [", round(conf.lower, digits), ", ", round(conf.upper, digits), "]),",
" margin of error: ±", round(error, digits),
sep=""))
}
@peterdalle
Copy link
Author

Examples:

> moe(p=0.50, n=8600)
[1] "Proportion: 50 % (95 % CI [48.94, 51.06]), margin of error: ±1.06"

> moe(p=0.01, n=8600, z=2.58, digits=3)
[1] "Proportion: 1 % (99 % CI [0.723, 1.277]), margin of error: ±0.277"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment