How to combine several chains from rjags into one chain in R?

I usually call JAGS from rjags with several chains for diagnostic purposes (e.g. 4 chains). After that, I often want to do some post-processing on the estimates of the back parameters (for example, use the predicted values, calculate additional statistics). However, at the moment this is a nuisance having chains stored in a list.

What is a good way to combine chains into a single parameter list?

+4
source share
2 answers

The package runjagshas a function combine.mcmc. Its default setting is to combine one or more chains and return one chain. For instance.

library(runjags)
fit <- combine.mcmc(multichainfit)

.

+5

rjags coda. , :

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"

( )

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

mcmc, 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

, start, end thin . , thin:

mcmc(do.call(rbind, smpls), thin=thin(smpls))

(, )

+1

All Articles