| Version: | 0.9-0 |
| Date: | 2026-11-24 |
| Title: | Using R to Run 'JAGS' |
| Author: | Yu-Sung Su |
| Maintainer: | Yu-Sung Su <suyusung@tsinghua.edu.cn> |
| BugReports: | https://github.com/suyusung/R2jags/issues/ |
| Depends: | R (≥ 2.14.0), rjags (≥ 5-2) |
| Suggests: | testthat (≥ 3.0.0) |
| Imports: | abind, coda (≥ 0.13), graphics, grDevices, methods, parallel, stats, stringr, utils |
| SystemRequirements: | JAGS (>= 5.0.0, https://mcmc-jags.sourceforge.io) |
| URL: | https://github.com/suyusung/R2jags |
| Description: | Providing wrapper functions to implement Bayesian analysis in JAGS. Some major features include monitoring convergence of a MCMC model using Rubin and Gelman Rhat statistics, automatically running a MCMC model till it converges, and implementing parallel processing of a MCMC model for multiple chains. |
| License: | GPL (> 2) |
| NeedsCompilation: | no |
| Config/roxygen2/version: | 8.1.1 |
| Packaged: | 2026-11-26 05:18:23 UTC; suyusung |
| Repository: | CRAN |
| Date/Publication: | 2026-11-30 03:30:09 UTC |
Extract an mcmc.list from a bugs object
Description
S3 method for as.mcmc.list: turns the
kept draws of an object of class "bugs" into an
mcmc.list, one mcmc per chain.
Usage
## S3 method for class 'list.bugs'
as.mcmc(x, ...)
Arguments
x |
an object of class |
... |
further arguments passed to methods. |
Value
An mcmc.list with x$n.chains chains.
Attach/detach elements of ‘JAGS’ objects to search path
Description
These attach or detach the three-way-simulation array of a bugs object to the
search path, so that the elements of sims.list can be referred to by
name. They do what R2WinBUGS::attach.bugs and
R2WinBUGS::detach.bugs do, and until 0.9-0 the package carried a
dependency on R2WinBUGS for their sake alone (issue #3).
Usage
attach.jags(x, overwrite = NA)
detach.jags()
Arguments
x |
An |
overwrite |
If |
Details
See the examples in jags for the usage.
Author(s)
Yu-Sung Su suyusung@tsinghua.edu.cn
References
Sibylle Sturtz and Uwe Ligges and Andrew Gelman. (2005). “R2WinBUGS: A Package for Running WinBUGS from R.” Journal of Statistical Software 3 (12): 1–6.
Examples
# See the example in ?jags for the usage.
Function for auto-updating ‘JAGS’ until the model converges
Description
The autojags function takes a rjags object as input. autojags
will update the model until it converges.
Usage
autojags(
object,
n.iter = 1000,
n.thin = 1,
Rhat = 1.1,
n.update = 2,
refresh = n.iter/50,
progress.bar,
...
)
Arguments
object |
an object of |
n.iter |
number of total iterations per chain, default=1000 |
n.thin |
thinning rate. Must be a positive integer, default=1 |
Rhat |
convergence criterion, default=1.1. |
n.update |
the max number of updates, default=2. |
refresh |
refresh frequency for progress bar, default is
|
progress.bar |
type of progress bar. Possible values are
“text”, “gui”, and “none”. Type “text” is
displayed on the R console. Type “gui” is a graphical progress bar
in a new window. The progress bar is suppressed if |
... |
further arguments passed to or from other methods. |
Author(s)
Yu-Sung Su suyusung@tsinghua.edu.cn
References
Gelman, A., Carlin, J.B., Stern, H.S., Rubin, D.B. (2003): Bayesian Data Analysis, 2nd edition, CRC Press.
Examples
# see ?jags for an example.
Retrieves the information from the JAGS compilation
Description
Retrieves the information from the JAGS compilation
Usage
count_nodes(x, ...)
Arguments
x |
A 'rjags' object (obtained from running |
... |
Additional parameters that can be passed |
Value
A vector with the number of observed, unobserved and total nodes included in the DAG resulting from the model assumptions encoded by the code.
Author(s)
Gianluca Baio
Examples
# An example model file is given in:
model.file <- system.file(package="R2jags", "model", "schools.txt")
#=================#
# initialization #
#=================#
# data
J <- 8.0
y <- c(28.4,7.9,-2.8,6.8,-0.6,0.6,18.0,12.2)
sd <- c(14.9,10.2,16.3,11.0,9.4,11.4,10.4,17.6)
jags.data <- list("y","sd","J")
jags.params <- c("mu","sigma","theta")
jags.inits <- function(){
list("mu"=rnorm(1),"sigma"=runif(1),"theta"=rnorm(J))
}
jagsfit <- jags(data=list("y","sd","J"), inits=jags.inits, jags.params,
n.iter=10, model.file=model.file)
count_nodes(jagsfit)
Run ‘JAGS’ from R
Description
The jags function takes data and starting values as input. It
automatically writes a jags script, calls the model, and saves the
simulations for easy access in R.
Usage
jags(
data,
inits,
parameters.to.save,
model.file = "model.bug",
n.chains = 3,
n.iter = 2000,
n.burnin = floor(n.iter/2),
n.thin = max(1, floor((n.iter - n.burnin)/1000)),
DIC = TRUE,
pD = FALSE,
n.iter.pd = NULL,
n.adapt = 100,
working.directory = NULL,
jags.seed = 123,
refresh = n.iter/50,
progress.bar,
digits = 5,
RNGname = c("Wichmann-Hill", "Marsaglia-Multicarry", "Super-Duper", "Mersenne-Twister"),
jags.module = c("glm", "dic"),
quiet,
checkMissing = FALSE,
initrep = NULL,
n.threads = NULL
)
jags2(
data,
inits,
parameters.to.save,
model.file = "model.bug",
n.chains = 3,
n.iter = 2000,
n.burnin = floor(n.iter/2),
n.thin = max(1, floor((n.iter - n.burnin)/1000)),
DIC = TRUE,
jags.path = "",
working.directory = NULL,
clearWD = TRUE,
refresh = n.iter/50
)
jags.parallel(
data,
inits,
parameters.to.save,
model.file = "model.bug",
n.chains = 2,
n.iter = 2000,
n.burnin = floor(n.iter/2),
n.thin = max(1, floor((n.iter - n.burnin)/1000)),
n.cluster = n.chains,
DIC = TRUE,
working.directory = NULL,
jags.seed = 123,
digits = 5,
RNGname = c("Wichmann-Hill", "Marsaglia-Multicarry", "Super-Duper", "Mersenne-Twister"),
jags.module = c("glm", "dic"),
export_obj_names = NULL,
envir = .GlobalEnv,
initrep = NULL,
n.threads = NULL
)
Arguments
data |
(1) a vector or list of the names of the data objects used by the model, (2) a (named) list of the data objects themselves, or (3) the name of a "dump" format file containing the data objects, which must end in ".txt", see example below for details. |
inits |
a list with |
parameters.to.save |
character vector of the names of the parameters to save which should be monitored. |
model.file |
file containing the model written in |
n.chains |
number of Markov chains (default: 3) |
n.iter |
number of total iterations per chain (including burn in; default: 2000) |
n.burnin |
length of burn in, i.e. number of iterations to discard at
the beginning. Default is |
n.thin |
thinning rate. Must be a positive integer. Set |
DIC |
logical; if |
pD |
logical; if |
n.iter.pd |
number of iterations to feed 'rjags::dic.samples()' to compute 'pD'. Defaults at 1000. |
n.adapt |
number of iterations for which to run the adaptation, when creating the model object. Defaults at 100. |
working.directory |
sets working directory during execution of this function; This should be the directory where model file is. |
jags.seed |
random seed for |
refresh |
refresh frequency for progress bar, default is
|
progress.bar |
type of progress bar. Possible values are
“text”, “gui”, and “none”. Type “text” is
displayed on the R console. Type “gui” is a graphical progress bar
in a new window. The progress bar is suppressed if |
digits |
as in |
RNGname |
the name for random number generator used in JAGS. There are
four RNGs supplied by the base module in JAGS: |
jags.module |
the vector of jags modules to be loaded. Default are “glm” and “dic”. Input NULL if you don't want to load any jags module. |
quiet |
Logical, whether to suppress stdout in |
checkMissing |
Default: FALSE. When TRUE, checks for missing data in
categorical parameters and returns a |
initrep |
number of replicate samples that JAGS draws from the prior
when it initializes unobserved stochastic nodes automatically; passed on
to |
n.threads |
number of threads that JAGS uses for sampling, passed on
to |
jags.path |
directory that contains the |
clearWD |
indicating whether the files ‘data.txt’,
‘inits[1:n.chains].txt’, ‘codaIndex.txt’, ‘jagsscript.txt’,
and ‘CODAchain[1:nchains].txt’ should be removed after |
n.cluster |
number of clusters to use to run parallel chains. Default equals n.chains. |
export_obj_names |
character vector of objects to export to the clusters. |
envir |
default is .GlobalEnv |
Details
To run:
Write a
JAGSmodel in an ASCII file.Go into R.
Prepare the inputs for the
jagsfunction and run it (see Example section).The model will now run in
JAGS. It might take a while. You will see things happening in the R console.
Author(s)
Yu-Sung Su suyusung@tsinghua.edu.cn, Masanao Yajima yajima@bu.edu, Gianluca Baio g.baio@ucl.ac.uk
References
Plummer, Martyn (2003) “JAGS: A program for analysis of Bayesian graphical models using Gibbs sampling.” https://www.r-project.org/conferences/DSC-2003/Proceedings/Plummer.pdf.
Gelman, A., Carlin, J. B., Stern, H.S., Rubin, D.B. (2003) Bayesian Data Analysis, 2nd edition, CRC Press.
Sibylle Sturtz and Uwe Ligges and Andrew Gelman. (2005). “R2WinBUGS: A Package for Running WinBUGS from R.” Journal of Statistical Software 3 (12): 1–6.
Examples
# Can set global options for some of the features of R2jags. For example
# running the command
options(r2j.pb="none")
# before launching jags shuts down the progress bar. Or running the command
options(r2j.quiet=TRUE)
# forces jags to not show the compilation summary. Or running the command
options(r2j.print.program=FALSE)
# modifies the print method and prevents R2jags from printing the name of
# software used to run the MCMC analysis. These options may be helpful
# when using Rmarkdown or quarto to help formatting the output.
#
# An example model file is given in:
model.file <- system.file(package="R2jags", "model", "schools.txt")
# Let's take a look:
file.show(model.file)
#=================#
# Initialization #
#=================#
# Data
J <- 8.0
y <- c(28.4, 7.9, -2.8, 6.8, -0.6, 0.6, 18.0, 12.2)
sd <- c(14.9, 10.2, 16.3, 11.0, 9.4, 11.4, 10.4, 17.6)
jags.data <- list(y = y, sd = sd, J = J)
jags.params <- c("mu", "sigma", "theta")
jags.inits <- function() {
list(mu = rnorm(1), sigma = runif(1), theta = rnorm(J))
}
## You can input data in 4 ways:
# 1) Data as a list of character strings
jagsfit <- jags(data = list("y", "sd", "J"), inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 10, model.file = model.file)
# 2) Data as a character vector of names
jagsfit <- jags(data = c("y", "sd", "J"), inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 10, model.file = model.file)
# 3) Data as a named list
jagsfit <- jags(data = list(y = y, sd = sd, J = J), inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 10, model.file = model.file)
# 4) Data from a file
fn <- "tmpbugsdata.txt"
dump(c("y", "sd", "J"), file = fn)
jagsfit <- jags(data = fn, inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 10, model.file = model.file)
unlink("tmpbugsdata.txt")
## Writing a BUGS model as an R function
schoolsmodel <- function() {
for (j in 1:J) {
y[j] ~ dnorm(theta[j], tau.y[j]) # Likelihood
tau.y[j] <- pow(sd[j], -2) # Precision
}
for (j in 1:J) {
theta[j] ~ dnorm(mu, tau) # Hierarchical model
}
tau <- pow(sigma, -2)
mu ~ dnorm(0.0, 1.0E-6)
sigma ~ dunif(0, 1000)
}
jagsfit <- jags(data = jags.data, inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 10, model.file = schoolsmodel)
#=================================#
# Running JAGS and postprocessing #
#=================================#
jagsfit <- jags(data = jags.data, inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 5000, model.file = model.file)
## Computing DIC with pD
## Not run:
jagsfit.pD <- jags(data = jags.data, inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 5000, model.file = model.file, pD = TRUE)
## End(Not run)
## Running JAGS in parallel
## Not run:
jagsfit.p <- jags.parallel(data = jags.data, inits = jags.inits,
parameters.to.save = jags.params,
n.iter = 5000, model.file = model.file)
print(jagsfit.p,digits=3,interval=c(0.025,0.975))
plot(jagsfit.p)
## End(Not run)
## Checking model convergence
## Not run:
traceplot(jagsfit)
traceplot(jagsfit.p)
## End(Not run)
## Updating JAGS if the model does not converge
## Not run:
jagsfit.upd <- update(jagsfit, n.iter = 100)
print(jagsfit.upd)
plot(jagsfit.upd)
## End(Not run)
## Auto-updating until convergence
## Not run:
jagsfit.upd <- autojags(jagsfit)
jagsfit.upd <- autojags(jagsfit.p)
## End(Not run)
## Obtaining DIC separately
## Not run:
dic.samples(jagsfit.upd$model, n.iter = 1000, type = "pD")
## End(Not run)
## Attaching and detaching JAGS results
## Not run:
attach.jags(jagsfit.upd)
mu # View parameter estimates
detach.jags()
## End(Not run)
## Picking up the last saved session
## Not run:
recompile(jagsfit)
jagsfit.upd <- update(jagsfit, n.iter = 100)
## End(Not run)
Read jags output files in CODA format
Description
This function reads Markov Chain Monte Carlo output in the CODA format
produced by JAGS and returns an object of class
mcmc.list for further output analysis using the
coda package.
Usage
jags2bugs(
path = getwd(),
parameters.to.save,
n.chains = 3,
n.iter = 2000,
n.burnin = 1000,
n.thin = 2,
DIC = TRUE
)
Arguments
path |
sets working directory during execution of this function; This should be the directory where CODA files are. |
parameters.to.save |
character vector of the names of the parameters to save which should be monitored. |
n.chains |
number of Markov chains (default: 3) |
n.iter |
number of total iterations per chain (including burn in; default: 2000) |
n.burnin |
length of burn in, i.e. number of iterations to discard at the beginning. Default is 1000, that is, discarding the first half of the default 2000 simulations. |
n.thin |
thinning rate, default is 2 |
DIC |
logical; if |
Author(s)
Yu-Sung Su suyusung@tsinghua.edu.cn, Masanao Yajima yajima@stat.columbia.edu
Print a bugs object
Description
S3 method for print: shows the model,
the sampling scheme, the summary table and (when available) the DIC
information of an object of class "bugs".
Usage
## S3 method for class 'bugs'
print(x, digits.summary = 1, ...)
Arguments
x |
an object of class |
digits.summary |
number of decimal places for the summary table. |
... |
further arguments passed to |
Value
x, invisibly.
Function for recompiling rjags object
Description
The recompile function takes a rjags object as input. recompile
will re-compile the previous saved rjags object.
Usage
recompile(object, n.iter, refresh, progress.bar)
Arguments
object |
an object of |
n.iter |
number of iterations for adaptation, default is 100 |
refresh |
refresh frequency for progress bar, default is
|
progress.bar |
type of progress bar. Possible values are
“text”, “gui”, and “none”. Type “text” is
displayed on the R console. Type “gui” is a graphical progress bar
in a new window. The progress bar is suppressed if |
Author(s)
Yu-Sung Su suyusung@tsinghua.edu.cn
Examples
# see ?jags for an example.
Trace plot of a bugs object
Description
Displays a plot of iterations vs. sampled values for each variable in the chain, with a separate plot per variable.
Usage
traceplot(x,...)
## S4 method for signature 'rjags'
traceplot(
x,
mfrow = c(1, 1),
varname = NULL,
match.head = TRUE,
ask = TRUE,
col = rainbow(x$n.chains),
lty = 1,
lwd = 1,
...
)
Arguments
x |
A bugs object |
mfrow |
graphical parameter (see |
varname |
vector of variable names to plot |
match.head |
matches the variable names by the beginning of the variable names in bugs object |
ask |
logical; if |
col |
graphical parameter (see |
lty |
graphical parameter (see |
lwd |
graphical parameter (see |
... |
further graphical parameters |
Author(s)
Masanao Yajima yajima@stat.columbia.edu.