Exact Binomial

this gives the exact p-value from the known distribution

#exact binomial test (declare values early and keep using them)
x_obs<-50
n<-75
p0<-0.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

Simulated Binomial

#binomial simulation method
#we are drawing from the hull distribution to run a hypothetical simulation to test the null hypothesis
nsim<-10000

nullDist<-rbinom(nsim, 75, 0.5)

hist(nullDist)
abline(v=50, col="red", lwd=2, lty=2)

head(nullDist)
## [1] 44 36 29 40 32 40
head(nullDist>=50)
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
mean(nullDist>=50)
## [1] 0.003
#still end up rejecting the null

Hypothesis Testing and CI

# Normal Aprroximation

#check the conditons
n*p0
## [1] 37.5
n*(1-p0)
## [1] 37.5
#hypothesis testing
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
## [1] 2.886751
pnorm(test_stat, lower.tail = FALSE)
## [1] 0.001946209
#confidence interval

#contruct margin of error with critical value and standard error
critval<-qnorm(0.975)
critval
## [1] 1.959964
SE<-sqrt(p_hat*(1-p_hat)/n)
SE
## [1] 0.05443311
#to create a plus or minus with the concatinate function
p_hat+c(-1,1)*critval*SE
## [1] 0.5599797 0.7733536
#melennials support same sex marriage more than the general population