Search code examples
plotrunjags

Plotting specific variable in runjags output


When plotting runjags output, how does one plot a single specific variable, when many other variables have similar names? Providing a quoted variable name with the varsargument doesn't seem to do it (it still provides all partial matches).

Here is a simple reproducible example.

N <- 200
nobs <- 3
psi <- 0.35
p <- 0.45
z <- rbinom(n=N, size=1,prob=psi)
y <- rbinom(n=N, size=nobs,prob=p*z)

sink("model.txt")
cat("
model {
for (i in 1:N){
    z[i] ~ dbern(psi)
    pz[i] <- z[i]*p
    y[i] ~ dbin(pz[i],nobs) 
    } #i
psi ~ dunif(0,1)
p ~ dunif(0,1)
}                                                   
",fill = TRUE)
sink()

m <-list(y=y,N=N,nobs=nobs)
inits <- function(){list(psi=runif(1),p=runif(1),z=as.numeric(y>0))}  
parameters <- c("p","psi")

ni <- 1000
nt <- 1
nb <- 200
nc <- 3
ad <- 100

library(runjags)

out <- run.jags(model="model.txt",monitor=parameters,data=m,n.chains=nc,inits=inits,burnin=nb,
    sample=ni,adapt=ad,thin=nt,modules=c("glm","dic"),method="parallel")

windows(9,4)
plot(out,plot.type=c("trace","histogram"),vars="p",layout=c(1,2),new.window=FALSE)

Solution

  • It should be possible to double quote variables to get an exact match, but this seems to be broken. It should also be possible to specify a logical vector to vars but this seems to be broken for the plot method ... how embarrassing. The following does work though:

    # Generate a logical vector to use with matching variable names:
    variables <- extract(out, 'stochastic')
    variables['psi'] <- FALSE
    
    # Add summary statistics only for the specified variables and pre-draw plots:
    out2 <- add.summary(out, vars=variables, plots=TRUE)
    
    plot(out2, plot.type=c("trace","histogram"))
    

    I will fix the other issues for the next release.

    Matt