# Roger Palay copyright 2016-02-27 # Saline, MI 48176 # ci_prop <- function( n, x, cl=0.95) { # compute a confidence interval for the # proportion given the sample size, the # number of items with the characteristic, # and the confidence level # do a few checks on the information given if( cl <=0.0 | cl >= 1 ) {return("Confidence level needs to be between 0 and 1")} if( x < 10) {return("Need at least 10 items with the characteristic")} if( n-x < 10) {return("Need at lease 10 items without the characteristic")} # we have no way to check if we are sampling < 5% # of the population p_hat <- x/n p_hat_sd <- sqrt(p_hat*(1-p_hat)/n) alpha_div_2 <- (1-cl)/2 z <- abs( qnorm( alpha_div_2)) lower <- p_hat - z*p_hat_sd upper <- p_hat + z*p_hat_sd if(lower < 0) { lower<-0} if(upper > 1 ) { upper <- 1} result<-c(lower, upper, p_hat, z, p_hat_sd) names(result) <- c("lower", "upper", "p hat", "z-score", "p hat sd") return( result ) }