The posterior model

Bayesian Modeling with RJAGS

Alicia Johnson

Associate Professor, Macalester College

Bayesian election model

prior: $p \sim \text{Beta}(45, 55)$

Bayesian Modeling with RJAGS

Bayesian election model

Prior: $p \sim \text{Beta}(45, 55)$

Likelihood: $X \sim \text{Beta}(10, p)$

Bayesian Modeling with RJAGS

Bayesian election model

Prior: $p \sim \text{Beta}(45, 55)$

Likelihood: $X \sim \text{Bin}(10, p)$

Bayesian Modeling with RJAGS

Posterior model of p

Prior: $p \sim \text{Beta}(45, 55)$

Likelihood: $X \sim \text{Bin}(10, p)$

Bayes' Rule:
posterior $\propto$ prior $\times$ likelihood

Bayesian Modeling with RJAGS

Getting started with RJAGS

RJAGS combines the power of R with the JAGS (Just Another Gibbs Sampler) engine. To get started:

  • Download the JAGS program outside R
  • Within R, install the rjags package
Bayesian Modeling with RJAGS

Bayesian models in RJAGS: DEFINE

# DEFINE the model
vote_model <- "model{
    # Likelihood model for X
    X ~ dbin(p, n)

    # Prior model for p
    p ~ dbeta(a, b)
}"
  • $X \sim \text{Bin}(n, p)$
  • $p \sim \text{Beta}(a, b)$
  • Warning:
    the rjags function dbin() is different than base dbinom()
Bayesian Modeling with RJAGS

Bayesian models in RJAGS: COMPILE

# DEFINE the model
vote_model <- "model{
    # Likelihood model for X
    X ~ dbin(p, n)

    # Prior model for p
    p ~ dbeta(a, b)
}"

# COMPILE the model    
vote_jags_A <- jags.model(textConnection(vote_model), 
    data = list(a = 45, b = 55, X = 6, n = 10),
    inits = list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = 100))
Bayesian Modeling with RJAGS

Bayesian models in RJAGS: SIMULATE

# DEFINE the model
vote_model <- "model{
    # Likelihood model for X
    X ~ dbin(p, n)   
    # Prior model for p
    p ~ dbeta(a, b)
}"
# COMPILE the model    
vote_jags <- jags.model(textConnection(vote_model), 
    data = list(a = 45, b = 55, X = 6, n = 10),
    inits = list(.RNG.name = "base::Wichmann-Hill", .RNG.seed = 100))
# SIMULATE the posterior
vote_sim <- coda.samples(model = vote_jags, 
    variable.names = c("p"), 
    n.iter = 10000)
Bayesian Modeling with RJAGS

Bayesian models in RJAGS: SIMULATE

# PLOT the simulated posterior
plot(vote_sim, trace = FALSE)

Bayesian Modeling with RJAGS

Let's practice!

Bayesian Modeling with RJAGS

Preparing Video For Download...