```{r, echo = FALSE}
knitr::opts_chunk$set(
  fig.path = "README_figs/README-"
)
```

# jagsUI: Run JAGS from R

<!-- badges: start -->
[![CRAN status](https://www.r-pkg.org/badges/version/jagsUI)](https://cran.r-project.org/web/packages/jagsUI/index.html)
[![R build status](https://github.com/kenkellner/jagsUI/workflows/R-CMD-check/badge.svg)](https://github.com/kenkellner/jagsUI/actions)
<!-- badges: end -->

This package runs `JAGS` (Just Another Gibbs Sampler) analyses from within `R`. It acts as a wrapper and alternative interface for the functions in the `rjags` package and adds some custom output and graphical options. It also makes running chains in parallel quick and easy.

## Installation

You can install the package from [CRAN](https://cran.r-project.org/web/packages/jagsUI/index.html), or get the development version from Github:

```r
devtools::install_github('kenkellner/jagsUI')
```

You will also need to separately install JAGS, which you can download [here](https://sourceforge.net/projects/mcmc-jags/files/JAGS/4.x/).

## Example

```{r}
library(jagsUI)
```

Format data:

```{r}
jags_data <- list(
  gnp = longley$GNP,
  employed = longley$Employed,
  n = nrow(longley)
)
```

Write BUGS model file:

```{r}
modfile <- tempfile()
writeLines("
model{

  # Likelihood
  for (i in 1:n){ 
    # Model data
    employed[i] ~ dnorm(mu[i], tau)
    # Calculate linear predictor
    mu[i] <- alpha + beta*gnp[i]
  }
    
  # Priors
  alpha ~ dnorm(0, 0.00001)
  beta ~ dnorm(0, 0.00001)
  sigma ~ dunif(0,1000)
  tau <- pow(sigma,-2)

}
", con=modfile)
```

Set initial values and parameters to save:

```{r}
inits <- function(){  
  list(alpha=rnorm(1,0,1),
       beta=rnorm(1,0,1),
       sigma=runif(1,0,3)
  )  
}

params <- c('alpha','beta','sigma')
```

Run JAGS:

```{r}
out <- jags(data = jags_data,
            inits = inits,
            parameters.to.save = params,
            model.file = modfile,
            n.chains = 3,
            n.adapt = 100,
            n.iter = 1000,
            n.burnin = 500,
            n.thin = 2)
```

View output:

```{r}
out
```

## Acknowledgments

* Martyn Plummer, developer of the excellent JAGS software package and the `rjags` R package.
* Andrew Gelman, Sibylle Sturtz, Uwe Ligges, Yu-Sung Su, and Masanao Yajima, developers of the `R2WinBUGS` and `R2jags` packages on which the package was originally based.
* Robert Swihart, Marc Kery, Jerome Guelat, Michael Schaub, and Mike Meredith who tested and provided helpful suggestions and improvements for the package.
