# R-program for Supplementary Exercise 8.62 of IPS7e succ <- c(63,43) patients <- c(78,77) # (b): confidence intervals # note: built-in function prop.test uses different method prop.test(succ, patients, conf.level=0.90, correct=F) # function to compute classical CI for difference between two proportions zprop2.ci = function(x, n, conf.level=0.95){ p <- x/n lower <- p[1]-p[2] - qnorm(1-(1-conf.level)/2)*sqrt(sum(p*(1-p)/n)) upper <- p[1]-p[2] + qnorm(1-(1-conf.level)/2)*sqrt(sum(p*(1-p)/n)) return(as.vector(c(lower,upper))) } # 90% classical CI zprop2.ci(succ, patients, conf.level=0.90) # (c): test # note: built-in function prop.test computes chi-square test (=z^2) zprop2.test = function(x, n, pdiff=0, alternative = c("two.sided")){ p <- x/n pc <- sum(x)/sum(n) z <- (p[1]-p[2]-pdiff)/sqrt(pc*(1-pc)*sum(1/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 zprop2.test(succ, patients)