####################################################################### ## Compute power of a one sample binomial test (the exact computation) ####################################################################### power.binom <- function(n, H0p, HAp, alpha = 0.05, alternative = "two.sided") { if((length(n) > 1) || is.na(n) || (n < 1) || (n != round(n))) stop("n must be a positive integer") if(!missing(H0p) && (length(H0p)>1 || is.na(H0p) || H0p<0 || H0p>1)) stop("H0p must be a single number between 0 and 1") if(!missing(HAp) && (length(HAp)>1 || is.na(HAp) || HAp<0 || HAp>1)) stop("HAp must be a single number between 0 and 1") if((length(alpha)>1 || is.na(alpha) || alpha<0 || alpha>1)) stop("alpha must be a single number between 0 and 1") CHOICES <- c("two.sided", "less", "greater") alternative <- CHOICES[pmatch(alternative, CHOICES)] if (length(alternative) > 1 || is.na(alternative)) stop("alternative must be \"two.sided\", \"less\" or \"greater\"") if (alternative == "less") { PP <- pbinom(0:n, n, H0p) RR <- length(PP[PP < alpha]) power <- sum(dbinom(0:(RR - 1), n, HAp)) } else if (alternative == "greater") { PP <- 1 - pbinom((-1):(n - 1), n, H0p) RR <- length(PP[PP < alpha]) power <- sum(dbinom((n - RR + 1):n, n, HAp)) } else { alpha <- alpha/2 PP <- pbinom(0:n, n, H0p) RR <- length(PP[PP < alpha]) temp <- sum(dbinom(0:(RR - 1), n, HAp)) PP <- 1 - pbinom((-1):(n - 1), n, H0p) RR <- length(PP[PP < alpha]) power <- sum(dbinom((n - RR + 1):n, n, HAp))+temp } power }