########################################################### ## this code compute the power of a chisq test comparing ## the equality of several proportions (rates). ## Input: ## pvec is the vector of several proportions. In most cases ## they are not all equal (alternative). ## ## nvec the sample sizes of several groups, its success proportion ## are been tested ########################################################### power.chisq <- function(pvec, nvec, alpha=0.05) { if( any(is.na(pvec)) || any(is.na(nvec)) ) stop("there are NA in the input") if(length(pvec) != length(nvec)) stop("pvec and nvec must be of same length") if( any(pvec >1) || any(pvec <0) ) stop("pvec must all between 0 and 1") if( any( nvec<0 ) ) stop("negative sample size?") v <- length(nvec) - 1 pbar <- sum(pvec * nvec)/sum(nvec) EH0 <- pbar * nvec EH0 <- c(EH0, nvec - EH0) EHA <- pvec * nvec EHA <- c(EHA, nvec - EHA) lambda <- sum((EHA - EH0)^2/EH0) 1 - pchisq(qchisq(1-alpha, df=v), df=v, ncp=lambda) }