Exact Binomial

This gives the exact p-value from the known distribution

#EXACT BINOM TEST
x_obs<-50
n<-75
p0<-.5
binom.test(x_obs, n, p0, alternative = "greater") 
## 
##  Exact binomial test
## 
## data:  x_obs and n
## number of successes = 50, number of trials = 75, p-value =
## 0.002614
## alternative hypothesis: true probability of success is greater than 0.5
## 95 percent confidence interval:
##  0.5665713 1.0000000
## sample estimates:
## probability of success 
##              0.6666667
#"greater" is a string, which is why it requires ""

Simulated Binomial

#BINOM SIM
nsim<-10000
nullDist<-rbinom(nsim, 75, .5) #this the null bc the null assumes this will be true
hist(nullDist) #shows histrogram of data output
abline(v=50, col="red", lwd=2, lty=2)

head(nullDist)
## [1] 32 30 36 35 43 36
head(nullDist>=50)#will give true and false responses
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
mean(nullDist>=50)#gives mean
## [1] 0.0027

Normal approximation

#check conditions
n*p0
## [1] 37.5
n*(1-p0)
## [1] 37.5
#hypothesis test
SE0<-sqrt(p0*(1-p0)/n)
SE0
## [1] 0.05773503
p_hat<-x_obs/n
p_hat
## [1] 0.6666667
test_stat<-(p_hat-p0)/SE0
test_stat #represents number of standard deviations (~3 is almost in the tails of distribution)
## [1] 2.886751
pnorm(test_stat, lower.tail=FALSE)
## [1] 0.001946209
#confidence interval
critVal<-qnorm(.975)#.975=area to the left (95% confidence interval + 2.5% in left tail)
critVal
## [1] 1.959964
SE<-sqrt(p_hat*(1-p_hat)/n)
SE
## [1] 0.05443311
p_hat+c(-1,1)*critVal*SE #c(-1,1) will run both the + and - scenario
## [1] 0.5599797 0.7733536