# functions for power and sample size calculation for the two-sample # t-test with equal (pooled) variances # copy this text and paste it into an R session, # or just type # source("http://www.stat.ncsu.edu/people/bloomfield/courses/st516/2sample.r") # at the R prompt. twoSamplePower = function(alpha, deltaMu, sigma, n1, n2 = n1) { # power of the two-sided two-sample t-test with pooled variance # alpha = size of test # deltaMu = difference of means # sigma = standard deviation of a single measurement # n1 = size of first sample # n2 = size of second sample if (alpha <= 0 || alpha >= 1) stop("alpha must be between 0 and 1"); if (sigma <= 0) stop("sigma must be positive"); if (n1 + n2 < 3) stop("combined sample sizes must be at least 3"); df = n1 + n2 - 2; tcrit = qt(1 - alpha / 2, df); ncp = abs(deltaMu) / (sigma * sqrt(1 / n1 + 1 / n2)); 1 - pt(tcrit, df, ncp) + pt(-tcrit, df, ncp); } twoSampleSize = function(alpha, deltaMu, sigma, targetPower) { # required sample size in the two-sided two-sample t-test with pooled # variance # alpha = size of test # deltaMu = difference of means # sigma = standard deviation of a single measurement # targetPower = desired power if (alpha <= 0 || alpha >= 1) stop("alpha must be between 0 and 1"); if (sigma <= 0) stop("sigma must be positive"); if (targetPower <= 0 || targetPower >= 1) stop("target power must be between 0 and 1"); p = 0; n = 1; while (p < targetPower) { n = n + 1; p = twoSamplePower(alpha, deltaMu, sigma, n); } list(SampleSize = n, ActualPower = p); }