# Roger Palay copyright 2016-01-31 # Saline, MI 48176 # hypoth_2test_prop <- function( x_one, n_one, x_two, n_two, H1_type, sig_level=0.05) { # perform a hypothsis test for the difference of # two proportions based on two samples. # H0 is that the proportions are equal, i.e., # their difference is 0 # The alternative hypothesis is # != if H1_type =0 # < if H1_type < 0 # > if H1_type > 0 # Do the test at sig_level significance. phat_one <- x_one / n_one phat_two <- x_two / n_two phat <- (x_one+x_two) / (n_one+n_two) std_err <- sqrt( phat*(1-phat)*(1/n_one +1/n_two) ) diff <- phat_one - phat_two if( H1_type==0) { z <- abs( qnorm(sig_level/2))} else { z <- abs( qnorm(sig_level))} to_be_extreme <- z*std_err decision <- "Reject" if( H1_type < 0 ) { crit_low <- - to_be_extreme crit_high = "n.a." if( diff > crit_low) { decision <- "do not reject"} attained <- pnorm( diff, mean=0, sd=std_err) alt <- "p_1 < p_2" } else if ( H1_type == 0) { crit_low <- - to_be_extreme crit_high <- to_be_extreme if( (crit_low < diff) & (diff < crit_high) ) { decision <- "do not reject"} if( diff < 0 ) { attained <- 2*pnorm(diff, mean=0, sd=std_err)} else { attained <- 2*pnorm(diff, mean=0, sd=std_err, lower.tail=FALSE) } alt <- "p_1 != p_2" } else { crit_low <- "n.a." crit_high <- to_be_extreme if( diff < crit_high) { decision <- "do not reject"} attained <- pnorm(diff, mean=0, sd=std_err, lower.tail=FALSE) alt <- "p_1 > p_2" } result <- c( alt, n_one, x_one, phat_one, n_two, x_two, phat_two, phat, std_err, z, crit_low, crit_high, diff, attained, decision) names(result) <- c("H1:", "n_one","x_one", "phat_one", "n_two","x_two", "phat_two", "pooled", "Std Err", "z extreme", "critical low", "critical high", "difference", "attained", "decision") return( result ) }