# Roger Palay copyright 2016-01-31 # Saline, MI 48176 # hypoth_test_prop <- function( H0_p, x, n, H1_type, sig_level=0.05) { # perform a hypothsis test for the proportion=H0_p # based on finding x items out of the n items in # the sample, where the alternative hypothesis is # != if H1_type==0 # < if H1_type < 0 # > if H1_type > 0 # Do the test at sig_level significance, # Do a little test to be sure we should do this. if( H0_p*n < 10 ) { return( "n*p must be >= 10") } if( (1-H0_p)*n < 10 ) { return( "n*(1-p) must be >=10" ) } min_pop_size = 20*n #get the s.d. of sample proportions sigma = sqrt(H0_p*(1-H0_p)/n) if(H1_type == 0 ) { z_score <- abs( qnorm( sig_level/2 ) ) } else { z_score <- abs( qnorm( sig_level ) ) } decision <- "Reject" samp_prop = x/n z = ( samp_prop - H0_p)/sigma if( H1_type == 0 ) { crit_low <- H0_p - z_score*sigma crit_high <- H0_p + z_score*sigma if( z < 0 ) { attained <- 2*pnorm( z ) } else { attained <- 2*pnorm(z, lower.tail=FALSE)} alt <- paste("prop != ", H0_p) } else if (H1_type < 0 ) { crit_low <- H0_p - z_score*sigma crit_high <- "n.a." attained <- pnorm( z ) alt <- paste("prop < ", H0_p) } else { crit_high <- H0_p + z_score*sigma crit_low <- "n.a." attained <- pnorm( z, lower.tail=FALSE ) alt <- paste("prop > ", H0_p) } if( attained > sig_level ) { decision <- "Do Not Reject" } result <- c(H0_p, alt, x, n, sig_level, sigma, z_score, crit_low, crit_high, samp_prop, z, attained, decision) names(result) <- c("H0_p","H1","x","n","sig level", "s.d. of prop", "z-score","crit low", "crit_high", "samp prop", "z", "attained", "decision") return( result ) }