1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
---
output:
md_document:
variant: gfm
---
```{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.
|