Here is the rjags
and coda
solution. Say you generate two chains like this:
library(rjags)
x <- rnorm(100)
model.str <- 'model {for (i in 1:100) {
x[i] ~ dnorm(mu, sd)}
mu ~ dnorm(0, .0001)
sd ~ dgamma(0.1, 0.1)}'
jags <- jags.model(textConnection(model.str), data = list(x = x),n.chains=2)
smpls <- coda.samples(model=jags,n.iter=2,variable.names=c("mu","sd"))
smpls
# [[1]]
# Markov Chain Monte Carlo (MCMC) output:
# Start = 1
# End = 2
# Thinning interval = 1
# mu sd
# [1,] -0.09152588 0.9009973
# [2,] 0.05586651 1.0482184
#
# [[2]]
# Markov Chain Monte Carlo (MCMC) output:
# Start = 1
# End = 2
# Thinning interval = 1
# mu sd
# [1,] 0.06893182 0.7317955
# [2,] 0.13599206 0.8517304
#
# attr(,"class")
# [1] "mcmc.list"
You can combine the two (or arbitrarily many) chains into a matrix by
do.call(rbind, smpls)
# mu sd
# [1,] -0.09152588 0.9009973
# [2,] 0.05586651 1.0482184
# [3,] 0.06893182 0.7317955
# [4,] 0.13599206 0.8517304
If you want an object of class mcmc
, simply use the function mcmc
:
mcmc(do.call(rbind, smpls))
# [[1]]
# Markov Chain Monte Carlo (MCMC) output:
# Start = 1
# End = 4
# Thinning interval = 1
# mu sd
# [1,] -0.09152588 0.9009973
# [2,] 0.05586651 1.0482184
# [3,] 0.06893182 0.7317955
# [4,] 0.13599206 0.8517304
If you want, you can preserve the start
, end
, or thin
attribute of the original chain. For example to preserve thin
:
mcmc(do.call(rbind, smpls), thin=thin(smpls))
(Of course you cannot preserve all three attributes)