Skip to content

Instantly share code, notes, and snippets.

@MonkmanMH
Last active December 25, 2015 00:59
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 MonkmanMH/6891654 to your computer and use it in GitHub Desktop.
Save MonkmanMH/6891654 to your computer and use it in GitHub Desktop.
calculate confidence interval (binomial distribution) - function in R
# BINOMIAL CONFIDENCE INTERVAL CALCULATOR
#
# the binomial distribuion approximates the Normal distribution
# http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval
#
# read the data file
bin_data <- read.csv("bin_data.csv")
#
#
# the binomial confidence calculator function
BiNomConf <- function(P, n){
StanDev <- sqrt((P * (1-P)) / n) # where P is the proportion to be tested
ConfInt <- StanDev * 1.96 # where 1.96 is the Z value of the 95% confidence level (change to 1.645 for 90%; 2.58 for 99%)
return(ConfInt) # print the confidence interval
}
#
# set the parameters for the function
P <- bin_data$P # proportion (0 to 1)
n <- bin_data$n # number of respondents
#
# assign the ConfInt to the variable "ConfInt" in the data table
bin_data$ConfInt <- BiNomConf(P, n)
#
# calculate the upper and lower bounds of the confidence interval
# and assign the CIs to variables in the data table
bin_data$UpperCI <- (bin_data$P + bin_data$ConfInt)
bin_data$LowerCI <- (bin_data$P - bin_data$ConfInt)
#
# write the data table as a new csv file
write.csv(bin_data, file="bin_data_new.csv")
#
# -30-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment