Search code examples
rbayesianjagsrunjagsrjags

Remove a chain from a runjags object in R


I have a runjags object that has two chains that mixed very well (chains 1 and 3), and one that did not (chain 2). How can I go about trimming the runjags object to just contain chains 1 and 3?

Here is a reproducible example of generating a JAGS model using runjags (although, the chains here mix fine).

library(runjags)

#generate the data
x <- seq(1,10, by = 0.1)
y <- x + rnorm(length(x))

#write a jags model
j.model = "
model{
#this is the model loop.
for(i in 1:N){
y[i] ~dnorm(y.hat[i], tau)
y.hat[i] <- m*x[i]
}

#priors
m ~ dnorm(0, .0001)
tau <- pow(sigma, -2)
sigma ~ dunif(0, 100)
}
"

#put data in a list.
data = list(y=y, x=x, N=length(y))

#run the jags model.
jags.out <- run.jags(j.model,
                     data = data,
                     n.chains=3,
                     monitor=c('m'))

One way to achieve this is to convert the runjags object to a mcmc.list, then remove the chain using the following code:

trim.jags <- as.mcmc.list(jags.out)
trim.jags <- mcmc.list(trim.jags[[1]], trimjags[[3]])

However, once converted in this direction, the data cannot be put back into the runjags format. I would really like a solution that keeps the output in the runjags format, as my current workflows rely on that formatting generated by the runjags summary output.


Solution

  • Take a look at the (admittedly not very obviously named) divide.jags function:

    jags_13 <- divide.jags(jags.out, which.chains=c(1,3))                     
    jags_13
    extend.jags(jags_13)
    # etc
    

    Hopefully this does exactly what you want.

    Matt