# This R code computes sample sizes needed # to obtain specified power for a test of # the null hypothesis that two proportions # are equal. It also computes sample sizes # needed to obtain confidence intervals with # specified margin of error. This code is # posted as power2p.R # Specify the probability of success # for the first population p1 <- .58 # Specify the probability of success # for the second population p2 <- .50 # Enter power values power <- c(.8, .9, .95, .99) # Ener the type I error level alpha <- .05 za <- qnorm(1-alpha/2) za1 <- qnorm(1-alpha) nb <- length(power) p <- (p1+p2)/2 va <- p1*(1-p1)+p2*(1-p2) rp <- sqrt(2*p*(1-p)/va) # Obtain a sample size for each of # the requested power values zb <- qnorm(power) size <- ((za*rp+zb)^2)*va/((p1-p2)^2) size1 <- ((za1*rp+zb)^2)*va/((p1-p2)^2) # Increase sample size to next largest integer # and print results sizer <- ceiling(size) size1r <- ceiling(size1) cat("\n \n Sample sizes for testing equality of two proportions", "\n \n \n p1=",p1,"p2=", p2, "alpha=", alpha,"power=", power, "\n \n Sample sizes (2-sided test): " , sizer, "\n \n \n \n p1=",p1,"p2=", p2, "alpha=", alpha,"power=", power, "\n \n Sample sizes (1-sided test): " , size1r, "\n") # Compute sample size needed to obtain a # confidence interval for the difference # between the two proportions with a # specified margin of error # Enter the confidence level level <- c(0.95) # Enter desired margin of error me <- c(0.04, .02, .01) # Compute needed sample sizes alpha2 <- (1.0-level)/2 np <- length(me) one <- rep(1,np) n <-((qnorm(one-alpha2)/me)^2)*va n <- ceiling(n) percent <- level*100; cat("\n \n \n Sample sizes for ", percent, " percent confidence intervals: \n", "\n \n margin of error: ", me, " \n \n sample size: ", n, "\n")