Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating mcmc.list object in R

I have used JAGS called via rjags to produce the mcmc.list object foldD_samples, which contains trace monitors for a large number of stochastic nodes (>800 nodes).

I would now like to use R to compute a fairly complicated, scalar-valued function of these nodes, and write the output to an mcmc object so that I can use coda to summarize the posterior and run convergence diagnostics.

However, I haven't been able to figure out how get the posterior draws from foldD_samples into a dataframe. Any help much appreciated.

Here is the structure of the mcmc.list:

str(foldD_samples)
List of 3
 $ : mcmc [1:5000, 1:821] -0.667 -0.197 -0.302 -0.204 -0.394 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:821] "beta0" "beta1" "beta2" "dtau" ...
  ..- attr(*, "mcpar")= num [1:3] 4100 504000 100
 $ : mcmc [1:5000, 1:821] -0.686 -0.385 -0.53 -0.457 -0.519 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:821] "beta0" "beta1" "beta2" "dtau" ...
  ..- attr(*, "mcpar")= num [1:3] 4100 504000 100
 $ : mcmc [1:5000, 1:821] -0.492 -0.679 -0.299 -0.429 -0.421 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:821] "beta0" "beta1" "beta2" "dtau" ...
  ..- attr(*, "mcpar")= num [1:3] 4100 504000 100
 - attr(*, "class")= chr "mcmc.list"

Cheers, Jacob

like image 634
Jacob Socolar Avatar asked Nov 15 '15 15:11

Jacob Socolar


1 Answers

As it's a list structure you can use either of these methods to bind the matrices together.

do.call(rbind.data.frame, foldD_samples)

or

rbindlist(lapply(foldD_samples, as.data.frame)) # thanks to BenBolker

A mwe

library(rjags)
library(coda)
library(data.table)

mod <- textConnection("model {
  A ~ dnorm(0, 1)
  B ~ dnorm(0, 1)
}")

# evaluate
mod <- jags.model(mod, n.chains = 4, n.adapt = 50000) 
pos <- coda.samples(mod,  c("A", "B"),  10000)

out <- do.call(rbind.data.frame, pos)
out2 <- rbindlist(lapply(pos, as.data.frame))
all.equal(out, out2, check.attributes=FALSE)
like image 58
user20650 Avatar answered Oct 13 '22 12:10

user20650