In this vignette we describe how the results from a `JointAI`

model can be visualized, summarized and evaluated. We use the NHANES data for examples in cross-sectional data and the dataset simLong for examples in longitudinal data. For more info on these datasets, check out the vignette *Visualizing Incomplete Data*, in which the distributions of variables and missing values in both sets is explored.

The functions described in this section use, by default, the full MCMC sample and show only the parameters of the analysis model. Arguments `start`

, `end`

and `thin`

are available to select a subset of the MCMC samples that is used to calculate the summary. The argument `subset`

allows to control which part of the MCMC sample is returned and follows the same logic as the argument `monitor_params`

in `*_imp()`

. The use of these arguments is further explained below.

The posterior sample can be visualized by two commonly used plots: a traceplot, showing samples across iterations, or a plot of the empirical density of the posterior sample.

A traceplot shows the sampled values per chain and node throughout iterations. It allows to visually evaluate convergence and mixing of the chains, and can be obtained with the function `traceplot()`

:

When the sampler has converged the chains show one horizontal band, as in the above figure. Consequently, when traces show a trend convergence has not been reached and more iterations are necessary (e.g., using `add_samples()`

).

Graphical aspects of the traceplot can be controlled by specifying standard graphical arguments via the dots argument `"..."`

, which are passed to `matplot()`

. This allows to change color, linetype and -width, limits, etc. Arguments `nrow`

and/or `ncol`

can be supplied to set specific numbers of rows and columns for the layout of the grid of plots.

With the argument `use_ggplot`

it is possible to get a **ggplot2** version of the traceplot. It can be extended using standard **ggplot2** syntax.

The posterior distributions can also be visualized using the function `densplot()`

, which plots the empirical density per node per chain, or combining chains (when `joined = TRUE`

).

The argument `vlines`

takes a list of lists, containing specifications passed to `abline`

, and allows to add (vertical) lines to the plot, e.g., marking zero:

```
densplot(mod13a, ncol = 3, col = c("darkred", "darkblue", "darkgreen"),
vlines = list(list(v = rep(0, nrow(summary(mod13a)$stats)),
col = grey(0.8))))
```

or marking the posterior mean and 2.5% and 97.5% quantiles:

```
densplot(mod13a, ncol = 3,
vlines = list(list(v = summary(mod13a)$stats[, "Mean"], lty = 1,
lwd = 2),
list(v = summary(mod13a)$stats[, "2.5%"], lty = 2),
list(v = summary(mod13a)$stats[, "97.5%"], lty = 2)
)
)
```

Like with `traceplot()`

it is possible to use the **ggplot2** version of `densplot()`

when setting `use_ggplot = TRUE`

. Here, vertical lines can be added as additional layers:

```
# make a dataset containing the quantiles of the posterior sample:
library("reshape2")
quantDF <- melt(summary(mod13a)$stat[, c('2.5%', '97.5%')],
varnames = c('variable', 'quantile'))
# fit the complete-case version of the model
mod13a_cc <- lm(SBP ~ gender + WC + alc + creat, data = NHANES)
# make a dataset with coefficients and confidence intervals from the
# complete case analysis
ccDF <- data.frame(variable = c(names(coef(mod13a_cc)), 'sigma_SBP'),
coef = c(coef(mod13a_cc), summary(mod13a_cc)$sigma),
rbind(confint(mod13a_cc), c(NA, NA)),
stringsAsFactors = FALSE
)
# ggplot version, excluding tau_SBP from the plot:
p13a <- densplot(mod13a, ncol = 3, use_ggplot = TRUE, joined = TRUE,
subset = c(analysis_main = TRUE, tau_y = FALSE)) +
theme(legend.position = 'bottom')
# add vertical lines for the:
# - coefficient from the compl. case analysis
# - confidence intervals from the compl. case analysis
# - quantiles of the posterior distribution
p13a +
geom_vline(data = ccDF, aes(xintercept = coef, color = 'cc')) +
geom_vline(data = ccDF, aes(xintercept = X2.5.., color = 'cc'),
lty = 2, na.rm = T) +
geom_vline(data = ccDF, aes(xintercept = X97.5.., color = 'cc'),
lty = 2, na.rm = T) +
geom_vline(data = subset(quantDF, variable != 'tau_SBP'),
aes(xintercept = value, color = 'JointAI'), lty = 2) +
scale_color_manual(name = 'CI from model: ',
limits = c('JointAI', 'cc'),
values = c('blue', 'red'),
labels = c('JointAI', 'compl.case'))
```

A summary of the posterior distribution estimated in a `JointAI`

model can be obtained using the function `summary()`

.

The posterior summary consists of the mean, standard deviation and quantiles (by default the 2.5% and 97.5% quantiles) of the MCMC samples from all chains combined, as well as the tail probability (see below) and Gelman-Rubin criterion (see section below).

Additionally, some important characteristics of the MCMC samples on which the summary is based, is given. This includes the range and number of iterations (“Sample size per chain”), thinning interval and number of chains. Furthermore, the number of observations (number of rows in the data) is given.

```
summary(mod13a)
#>
#> Linear model fitted with JointAI
#>
#> Call:
#> lm_imp(formula = SBP ~ gender + WC + alc + creat, data = NHANES,
#> n.iter = 500)
#>
#> Posterior summary:
#> Mean SD 2.5% 97.5% tail-prob. GR-crit
#> (Intercept) 81.413 9.652 62.301 100.162 0.0000 1.00
#> genderfemale 0.338 2.545 -4.765 5.274 0.8600 1.01
#> WC 0.303 0.076 0.151 0.455 0.0000 1.00
#> creat 7.753 7.474 -6.942 22.775 0.3160 1.02
#> alc>=1 6.310 2.435 1.361 11.147 0.0133 1.00
#>
#> Posterior summary of residual std. deviation:
#> Mean SD 2.5% 97.5% GR-crit
#> sigma_SBP 14.4 0.756 12.9 16 1
#>
#>
#> MCMC settings:
#> Iterations = 101:600
#> Sample size per chain = 500
#> Thinning interval = 1
#> Number of chains = 3
#>
#> Number of observations: 186
```

For mixed models, `summary()`

also returns the posterior summary of the random effects covariance matrix `D`

and the number of groups:

```
library(splines)
mod13b <- lme_imp(bmi ~ GESTBIR + ETHN + HEIGHT_M + ns(age, df = 3),
random = ~ ns(age, df = 3) | ID, data = simLong,
n.iter = 250)
summary(mod13b)
#>
#> Linear mixed model fitted with JointAI
#>
#> Call:
#> lme_imp(fixed = bmi ~ GESTBIR + ETHN + HEIGHT_M + ns(age, df = 3),
#> data = simLong, random = ~ns(age, df = 3) | ID, n.iter = 250)
#>
#> Posterior summary:
#> Mean SD 2.5% 97.5% tail-prob. GR-crit
#> (Intercept) 11.49500 2.16529 7.15793 15.6651 0.0000 1.00
#> GESTBIR 0.05889 0.03857 -0.01767 0.1352 0.1360 1.01
#> HEIGHT_M 0.00788 0.00828 -0.00817 0.0247 0.3040 1.00
#> ETHNother 0.25200 0.12860 -0.01946 0.4883 0.0667 1.02
#> ns(age, df = 3)1 -0.49074 0.08889 -0.65260 -0.3119 0.0000 1.07
#> ns(age, df = 3)2 3.12487 0.16317 2.80457 3.4421 0.0000 1.12
#> ns(age, df = 3)3 -0.83848 0.06684 -0.96557 -0.6987 0.0000 1.36
#>
#> Posterior summary of random effects covariance matrix:
#> Mean SD 2.5% 97.5% tail-prob. GR-crit
#> D[1,1] 1.858 0.159 1.573 2.173 1.06
#> D[1,2] -0.951 0.154 -1.252 -0.678 0 1.00
#> D[2,2] 2.110 0.252 1.660 2.609 1.62
#> D[1,3] -2.329 0.306 -2.923 -1.768 0 1.08
#> D[2,3] 2.429 0.333 1.871 3.158 0 1.07
#> D[3,3] 7.845 0.770 6.485 9.477 1.11
#> D[1,4] -0.588 0.120 -0.837 -0.377 0 1.11
#> D[2,4] 1.198 0.139 0.935 1.466 0 1.07
#> D[3,4] 1.856 0.285 1.324 2.466 0 1.19
#> D[4,4] 1.068 0.151 0.819 1.431 1.03
#>
#> Posterior summary of residual std. deviation:
#> Mean SD 2.5% 97.5% GR-crit
#> sigma_bmi 0.692 0.0105 0.673 0.713 1.16
#>
#>
#> MCMC settings:
#> Iterations = 101:350
#> Sample size per chain = 250
#> Thinning interval = 1
#> Number of chains = 3
#>
#> Number of observations: 3894
#> Number of groups: 499
```

The tail probability, calculated as \(2\times\min\left\{Pr(\theta > 0), Pr(\theta < 0)\right\},\) where \(\theta\) is the parameter of interest, is a measure of how likely the value 0 is under the estimated posterior distribution. The figure visualizes three examples of posterior distributions and the corresponding minimum of \(Pr(\theta > 0)\) and \(Pr(\theta < 0)\) (shaded area):

By default, `summary()`

will only print the posterior summary for the main model parameters of the analysis model and use the whole MCMC sample. The argument `subset`

allows to control which part of the MCMC sample is returned and follows the same logic as the argument `monitor_params`

in `*_imp()`

. Arguments `start`

, `end`

and `thin`

are available to select a subset of the MCMC samples that is used to calculate the summary. The use of these arguments is further explained below).

Convergence of the MCMC chains and precision of the posterior sample can also be evaluated in a more formal manner. Implemented in **JointAI** are the Gelman-Rubin criterion for convergence^{1} and a comparison of the Monte Carlo Error with the posterior standard deviation.

The Gelman-Rubin criterion evaluates convergence by comparing within and between chain variability and, thus, requires at least two MCMC chains to be calculated. It is implemented for `JointAI`

objects in the function `GR_crit()`

, which is based on the function `gelman.diag()`

from the package **coda**. The upper limit of the confidence interval should not be much larger than 1.

```
GR_crit(mod13a)
#> Potential scale reduction factors:
#>
#> Point est. Upper C.I.
#> (Intercept) 1.001 1.00
#> genderfemale 1.001 1.01
#> WC 1.002 1.00
#> creat 1.006 1.02
#> alc>=1 1.001 1.00
#> sigma_SBP 0.999 1.00
#>
#> Multivariate psrf
#>
#> 1.01
```

Besides the arguments `start`

, `end`

, `thin`

, and `subset`

, which are explained below, `GR_crit()`

also takes the arguments of `gelman.diag()`

.

Precision of the MCMC sample can be checked with the function `MC_error()`

. It uses the function `mcmcse.mat()`

from the package **mcmcse** to calculate the Monte Carlo error (the error that is made since the sample is finite) and compares is to the standard deviation of the posterior sample. A rule of thumb is that the Monte Carlo error should not be more than 5% of the standard deviation.^{2}. Besides the arguments explained below, `MC_error()`

takes the arguments of `mcmcse.mat()`

.

```
MC_error(mod13a)
#> est MCSE SD MCSE/SD
#> (Intercept) 41.236 1.48438 43.6091 0.034
#> genderfemale 0.338 0.06767 2.5446 0.027
#> WC 0.021 0.00016 0.0052 0.030
#> creat 45.285 1.46823 43.6579 0.034
#> alc>=1 6.310 0.07893 2.4353 0.032
#> sigma_SBP 14.405 0.01771 0.7559 0.023
```

`MC_error()`

returns an object of class `MCElist`

, which is a list containing matrices with the posterior mean, estimated Monte Carlo error, posterior standard deviation and the ratio of the Monte Carlo error and posterior standard deviation, for the scaled and unscaled (transformed back to the scale of the data) posterior samples. The associated print method prints only the latter.

To facilitate quick evaluation of the Monte Carlo error to posterior standard deviation ratio, plotting of an object of class `MCElist`

using `plot()`

shows this ratio for each (selected) node and automatically adds a vertical line at the desired cut-off (by default 5%).

By default, the functions `traceplot()`

, `densplot()`

, `summary()`

, `GR_crit()`

and `MC_Error()`

use all iterations of the MCMC sample and consider only the parameters of the analysis model (if they were monitored). In this section we describe how the set of iterations and parameters to display can be changed using the arguments `subset`

, `start`

, `end`

and `thin`

.

As long as the main parameters have been monitored in a `JointAI`

object, i.e., when `monitor_params`

was set to `TRUE`

, only these parameters are returned in the model summary, plots and criteria shown above. When the main parameters of the analysis model were not monitored, i.e., `monitor_params = c(analysis_main = FALSE)`

, and the argument `subset`

is not specified, all parameters that were monitored are displayed.

To display output for nodes other than the main parameters of the analysis model or for a subset of nodes, the argument `subset`

needs to be specified.

To display only the parameters of the imputation models, we set `subset = c(analysis_main = FALSE, imp_pars = TRUE)`

(after re-estimating the model with the monitor for these parameters switched on):

```
mod13c <- update(mod13a, monitor_params = c(imp_pars = TRUE))
summary(mod13c, subset = c(analysis_main = FALSE, imp_pars = TRUE))
#>
#> Linear model fitted with JointAI
#>
#> Call:
#> lm_imp(formula = SBP ~ gender + WC + alc + creat, data = NHANES,
#> n.iter = 500, monitor_params = c(imp_pars = TRUE))
#>
#> Posterior summary:
#> Mean SD 2.5% 97.5% tail-prob. GR-crit
#> alpha[1] 0.1649 0.101 -0.0292 0.3668 0.0947 1.001
#> alpha[2] -0.3554 0.144 -0.6512 -0.0642 0.0120 0.999
#> alpha[3] 0.4943 0.087 0.3275 0.6641 0.0000 1.003
#> alpha[4] -1.0421 0.133 -1.3078 -0.7902 0.0000 1.003
#> alpha[5] 0.0757 0.063 -0.0433 0.1972 0.2293 1.002
#> alpha[6] -0.1226 0.246 -0.5894 0.3742 0.6027 1.050
#> alpha[7] -0.9056 0.428 -1.7553 -0.1085 0.0187 1.046
#> alpha[8] 0.0916 0.167 -0.2376 0.4272 0.5960 1.044
#> alpha[9] -0.2613 0.200 -0.6758 0.0982 0.1907 1.037
#> tau_WC 1.0300 0.106 0.8319 1.2501 0.0000 1.004
#> tau_creat 1.4029 0.150 1.1197 1.7008 0.0000 1.014
#>
#>
#> MCMC settings:
#> Iterations = 101:600
#> Sample size per chain = 500
#> Thinning interval = 1
#> Number of chains = 3
#>
#> Number of observations: 186
```

To select only some of the parameters, they can be specified directly by name via the `other`

element of `subset`

.

This also works when a subset of the imputed values should be displayed:

```
# re-fit the model and monitor the imputed values
mod13d <- update(mod13a, monitor_params = c(imps = TRUE))
# select all imputed values for 'WC' (3rd column of Xc)
sub3 <- grep('Xc\\[[[:digit:]]+,3\\]', parameters(mod13d), value = TRUE)
sub3
#> [1] "Xc[33,3]" "Xc[150,3]"
# pass "sub3" to "subset" via "other", for example in a traceplot:
# traceplot(mod13d, subset = list(other = sub3), ncol = 2)
```

When the number of imputed values is large or in order to check convergence of random effects, it may not be feasible to plot and inspect all traceplots. In that case a random subset of, for instance the random effects, can be selected (output not shown):

```
# re-fit the model monitoring the random effects
mod13e <- update(mod13b, monitor_params = c(ranef = TRUE))
# exract random intercepts and random slopes
ri <- grep('^b\\[[[:digit:]]+,1\\]$', colnames(mod13e$MCMC[[1]]), value = T)
rs <- grep('^b\\[[[:digit:]]+,2\\]$', colnames(mod13e$MCMC[[1]]), value = T)
# to plot the chains of 12 randomly selected random intercepts and slopes:
traceplot(mod13e, subset = list(other = sample(ri, size = 12)), ncol = 4)
traceplot(mod13e, subset = list(other = sample(rs, size = 12)), ncol = 4)
```

With the arguments `start`

, `end`

and `thin`

it is possible to select which iterations from the MCMC sample are included in the summary. `start`

and `end`

specify the first and last iterations to be used, `thin`

the thinning interval. Specification of `start`

, thus, allows to discard a “burn-in”, i.e., the iterations before the MCMC chain had converged.

Often, the aim of an analysis is not only to estimate the association between outcome and covariates, but to predict future outcomes or outcomes for new subjects.

The function `predict()`

allows to obtain predicted values and corresponding prediction intervals from `JointAI`

objects. Note that for mixed models, currently, only marginal prediction but not prediction conditional on the random effects is implemented. A dataset containing data which the prediction should be performed is specified via the argument `newdata`

. The argument `quantiles`

allows to specify the quantiles of the posterior sample that are used to obtain the prediction interval (by default the 2.5% and 97.5% quantile). Arguments `start`

, `end`

and `thin`

control the subset of MCMC samples used.

```
predict(mod13a, newdata = NHANES[27, ])
#> $dat
#> SBP gender age race WC alc educ creat albu
#> 392 126.6667 male 32 Mexican American 94.1 <1 low 0.83 4.2
#> uricacid bili occup smoke fit 2.5% 97.5%
#> 392 8.7 1 <NA> former 116.342 112.5464 120.1822
#>
#> $fit
#> [1] 116.342
#>
#> $quantiles
#> [,1]
#> 2.5% 112.5464
#> 97.5% 120.1822
```

`predict()`

returns a list with elements `dat`

, `fit`

and `quantiles`

, containing `newdata`

with the predicted values and quantiles appended, the predicted values and quantiles that form the prediction interval.

Another reason to obtain predicted values is the visualization of non-linear effects. To facilitate the generation of a dataset for such a prediction, the function `predDF()`

can be used. It generates a `data.frame`

that contains a sequence of values through the range of observed values for a covariate specified by the argument `var`

, and the median or reference value for all other continuous and categorical variables.

```
# create dataset for prediction
newDF <- predDF(mod13b, var = "age")
# obtain predicted values
pred <- predict(mod13b, newdata = newDF)
# plot predicted values and prediction interval
matplot(pred$dat$age, pred$dat[, c('fit', '2.5%', '97.5%')],
lty = c(1,2,2), type = 'l', col = 1,
xlab = 'age in months', ylab = 'predicted value')
```

Imputed datasets can be extracted from a `JointAI`

object (in which a monitor for the imputed values has been set, i.e., `monitor_params = c(imps = TRUE)`

) and exported to SPSS (IBM SPSS Statistics, IBM Corp.) with the function `get_MIdat()`

. A completed dataset is created by taking the imputed values from a randomly chosen iteration of the MCMC sample, transforming them back to the original scale if scaling had been performed before the MCMC sampling, and filling them into the original incomplete data.

The argument `m`

specifies the number of imputed datasets to be created, `include`

controls whether the original data are included in the long format `data.frame`

(default is `include = TRUE`

), `start`

specifies the first iteration that may be used and `minspace`

is the minimum number of iterations between iterations eligible to be selected.

To make the selection of iterations to form the imputed data reproducible, a seed value can be specified via the argument `seed`

. When `export_to_SPSS = TRUE`

the imputed data is exported to SPSS, i.e., a `.txt`

file containing the data and a `.sps`

file containing SPSS syntax to convert the data into an SPSS data file (with ending `.sav`

) are written. Arguments `filename`

and `resdir`

allow to specify the name of the `.txt`

and `.sps`

file and the directory they are written to.

`get_MIdat()`

returns a long-format `data.frame`

containing the imputed datasets (and by default the original data) stacked onto each other. The imputation number is given in the variable `Imputation_`

, column `.id`

contains a newly created id variable for each observation in cross-sectional data (multi-level data should already contain an id variable).

Gelman, A. and Rubin, D.B. (1992). Inference from Iterative Simulation Using Multiple Sequences.

*Statistical Science***7**(4), 457-472. doi: 10.1214/ss/1177011136.

Brooks, S. P. and Gelman, A. (1998). General Methods for Monitoring Convergence of Iterative Simulations.*Journal of Computational and Graphical Statistics***7**(4), 434 - 455. doi: 10.1080/10618600.1998.10474787.↩Lesaffre, E. M. and A. B. Lawson (2012).

*Bayesian Biostatistics*. John Wiley & Sons. doi: 10.1002/9781119942412.↩