Search code examples
rjagsrjagsrunjags

trimming mcmc.list in jags / rjags / runjags


I have the output of a runjags model in R as an mcmc.list. Below is code to generate 3 chains of 1,000 samples. I'd like to trim all 12 chains to the last 400 samples. I can pull apart the chains and save matrices of chain output in a list, but its no longer an mcmc.list and I can't figure out how to turn it back into an mcmc.list.

Here are some data to run a runjags model, and convert the output to a mcmc.list:

y <- rnorm(100)

jags.model ="
model {
#model
for (i in 1:N){
      y[i] ~ dnorm(y.hat[i], tau) 
  y.hat[i] <- m0
}

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

jags.data <- list(y = y, N = length(y))
jags.out <- runjags::run.jags(jags.model,
                              data = jags.data,
                              n.chains = 3,
                              adapt = 100,
                              burnin = 100,
                              sample = 1000,
                              monitor = c('m0'))
z <- coda::as.mcmc.list(jags.out)

Solution

  • The easiest way to do this is using window:

    z2 <- window(z, start=601, end=1000, thin=1)
    summary(z2)
    

    See also:

    ?window.mcmc.list
    

    Alternatively, you could use as.mcmc and as.mcmc.list to convert your (list of) truncated matrices back into an mcmc.list object:

    library('coda')
    z3 <- as.mcmc.list(lapply(z, function(x) as.mcmc(x[601:1000,])))
    summary(z3)
    

    But I'd stick with using window if I were you!

    Matt