Category Archives: R

Example Bayesian Inference using R and OpenBUGS

  1. Open the R console
    Go to File/Change dir and set the working directory for R.
  2. Use your favorite editor to save the following code as schools.bug in your R working directory.
    model {
    for (j in 1:J){
    y[j] ~ dnorm (theta[j], tau.y[j])
    theta[j] ~ dnorm (mu.theta, tau.theta)
    tau.y[j] <- pow(sigma.y[j], -2)
    }
    mu.theta ~ dnorm (0.0, 1.0E-6)
    tau.theta <- pow(sigma.theta, -2)
    sigma.theta ~ dunif (0, 1000)
    }
  3. Save this data as schools.dat in your R working directory.
    school estimate sd
    A  28  15
    B   8  10
    C  -3  16
    D   7  11
    E  -1   9
    F   1  11
    G  18  10
    H  12  18
  4. Go back to the R console and type the following commands.
    schools <- read.table (“schools.dat”, header=TRUE)
    J <- nrow(schools)
    y <- schools$estimate
    sigma.y <- schools$sd
    data <- list (“J”, “y”, “sigma.y”)
    inits <- function(){list(theta=rnorm(J,0,100),mu.theta=rnorm(1,0,100),sigma.theta=runif(1,0,100))}
    parameters <- c(“theta”, “mu.theta”, “sigma.theta”)
    library (“BRugs”)

    schools.sim <- bugs (data, inits, parameters, “schools.bug”, n.chains=3, n.iter=1000, program=”openbugs”)

 

From an example at columbia.edu.

Bayesian Inference Using R

Here are the steps I took to create an environment for doing Bayesian Inference.

  1. Download and install R
    Find a mirror near you, download the executable, then run the install.
  2. Get familiar with the R environment
    Read the manual.
  3. Download and install OpenBUGS
    Go to OpenBUGS, pick an OS, download, and install.
  4. Go back to R and install the coda package (you will need this for BRugs)
    Open the R console and type install.packages(‘coda’).
    Choose a mirror, then finish install.
    Type library() at the console to verify coda is in the list of installed packages.
  5. Go back to R and install the BRugs package (you will need this to reference OpenBUGS from R)
    Open the R console and type install.packages(‘BRugs’).
    Type library(BRugs) at the console to open BRugs.