## Chapter 1 
##
## Code to support Video Vignette
##
## Videos and supporting code are not a complete portrayal
## of Chapter content.

## buddy's coin flips
data <- c("H", "T", "H", "H", "H", "T", "T", "H", "T", "T", "H", "H", "H",
          "T", "T", "H", "H", "H", "H", "T", "H", "H", "H", "T", "H", "H", "T", 
          "H", "T", "T")

## convert to binary
y <- as.numeric(data == "H")
n <- length(y)

## observed statistic
s <- sum(y) 

## MC Simulation
N <- 10000                        ## number of MC "trials"
Ss <- rep(NA, N)                  ## storage for sampled test statistics
for(i in 1:N) {                   ## each MC trial
  Ys <- rbinom(n, 1, 0.5)         ## generate n (=30) virtual coin flips
  Ss[i] <- sum(Ys)                ## calculate the test statistic
}

## visualizing simulation
hist(Ss, main="") 
abline(v=c(s, n-s), lty=1:2, col=2, lwd=2)
legend("topright", c("s", "reflect"), col=2, lty=1:2, lwd=2, bty="n")

## p-value calculation (two-sided "approximation")
pval <- 2*mean(Ss >= s)
pval
## for other, non-approximate alternatives, see book chapter
