# R-program for Supplementary Exercises 8.84 and 8.85 of IPS7e # 8.84: confidence intervals # note: built-in function prop.test uses different method prop.test(68, 100, conf.level=0.95) # function to compute classical CI for one proportion zprop.ci = function(x, n, conf.level=0.95){ p <- x/n lower <- p - qnorm(1-(1-conf.level)/2)*sqrt(p*(1-p)/n) upper <- p + qnorm(1-(1-conf.level)/2)*sqrt(p*(1-p)/n) return(as.vector(c(p,lower,upper))) } # classical (z) CI zprop.ci(68, 100) * plus four CI, manually constructed zprop.ci(70, 104) # "exact" CI based on the binomial distribution binom.test(68, 100, conf.level=0.95) # 8.85: tests # note: built-in function prop.test computes chi-square test (=z^2) prop.test(68, 100, p=0.75, correct=F) # function to compute classical z-test for one proportion zprop.test = function(x, n, p=0.5, alternative = c("two.sided")){ z <- (x/n-p)/sqrt(p*(1-p)/n) if (alternative == "two.sided") pval <- 2*pnorm(-abs(z)) if (alternative == "less") pval <- pnorm(z) if (alternative == "greater") pval <- pnorm(z, lower.tail=F) return(as.vector(c(z,pval))) } # z-test based on normal approximation zprop.test(68, 100, p=0.75) # exact test based on the binomial distribution - preferable! binom.test(68, 100, p=0.75)