7.5 A Beta-Binomial example

1 success in 2 trials

\[ Y|\pi = bin(2, \pi) \]

\[ \pi = Beta(2,3) \]

We are still playing “pretend”

We are moving for step 1 to an Uniform to a Beta model because we want \(\pi\) to be [0,1]. And we will draw every step from this Beta model. -> change in step 1

\[\alpha = min \{1, \frac{f(\pi_{proposal}|y)q(\pi)}{f(\pi|y) q(\pi_{proposal})} \} \]

one_iteration <- function(a, b, current){
 # STEP 1: Propose the next chain location
 proposal <- rbeta(1, a, b)
  
 # STEP 2: Decide whether or not to go there
 proposal_plaus <- dbeta(proposal, 2, 3) * dbinom(1, 2, proposal)
 proposal_q     <- dbeta(proposal, a, b) # <- new
 current_plaus  <- dbeta(current, 2, 3) * dbinom(1, 2, current)
 current_q      <- dbeta(current, a, b) # <- new
 alpha <- min(1, proposal_plaus / current_plaus * current_q / proposal_q)
 next_stop <- sample(c(proposal, current), 
                     size = 1, prob = c(alpha, 1-alpha))
  
 return(data.frame(proposal, alpha, next_stop))
}
betabin_tour <- function(N, a, b){
  # 1. Start the chain at location 0.5
  current <- 0.5

  # 2. Initialize the simulation
  pi <- rep(0, N)
  
  # 3. Simulate N Markov chain stops
  for(i in 1:N){    
    # Simulate one iteration
    sim <- one_iteration(a = a, b = b, current = current)
    
    # Record next location
    pi[i] <- sim$next_stop
    
    # Reset the current location
    current <- sim$next_stop
  }
  
  # 4. Return the chain locations
  return(data.frame(iteration = c(1:N), pi))
}