Created
July 13, 2017 19:59
-
-
Save peterdalle/215470af0d7d65102255027923c9963e to your computer and use it in GitHub Desktop.
Calculate margin of error from proportion, and return confidence interval
This file contains hidden or 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
| # 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="")) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples: