Solved – Using R2WinBUGS, how to extract information from each chain

bugsmarkov-chain-montecarlor

I am new to Gibbs Sampling, and have been using WinBUGS, but I find that it is not well-suited towards storing/presenting results, so I have been calling it from R using the R2WinBUGS package. The data is apparently stored as a "bug" class.

I converted it to coda to run diagnostics, and it displays each of the chains, but I am confused as to the $ extension for each individual chain. I cannot find any good documentation for the "coda" class (the cran instructions are not helpful).

My code is below:

> bugs.sim <- bugs(data, inits, parameter, "gl.bug", n.chains = 5,
                   codaPkg = TRUE, DIC = FALSE, n.iter = 5000)
> codaobject <- read.bugs(bugs.sim)

As you can see, I have 5 chains, and I would like to take the mean and standard deviation of each. How do I go about doing this? I can use the codaobject to take the Geweke diagnostic of each chain, it displays each chain as [[i]] ($i=1,\dots,5$).

Thanks in advance. And any references to a detailed documentation for R2Winbugs, would also be greatly appreciated.

Best Answer

The object returned by read.bugs is an object of S3 class mcmc.list. You can use the double brackets [[ to access the separate chains, i.e. the different mcmc-objects that make up the larger mcmc.list object, which really is simply a list of mcmc-objects that inherits some information about thinning and chain length from its components.

More to the point, s.th. like lapply(codaobject, function(x){ colMeans(x) }) should return the posterior means for each parameter in each chain and lapply(codaobject, function(x){ apply(x, 2, sd) }) should give chain- and parameter-specific posterior sd's, since each chain is essentially just a numeric matrix with rows corresponding to the (saved) iterations and columns corresponding to the different params.

EDIT: I think Gelman/Hill's "Bayesian Data Analysis" contains some worked examples using R2WinBUGS.

Related Question