---
title: "xamples for Bayesian Mediation Analysis with BART (bmabart)"
author: 
  - Qingzhao Yu & Bin Liu
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    keep_md: true
    fig_caption: yes
bibliography: vignettebib.bib
link-citations: true
vignette: >
  %\VignetteIndexEntry{xamples for Bayesian Mediation Analysis with BART (bmabart)}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  error=TRUE,
  warning=FALSE
)
```

## Package installation
R package bmabart is used for Bayesian Mediation Analysis based on the Bayesian Additive Regression Trees [-@Yu2025;-@Yu2022]. The mediation effect (ME) refers to the effect conveyed by intervening variables to an observed relationship between an exposure (predictor) and a response variable (outcome). In this package, the exposure is also called the predictor, the intervening variables (IV) are called mediators or confounders depending on the conceptual models. The ME include total effect, direct effect, and indirect effects from different IVs. The effects are defined in Yu et al. [-@Yu2014]. The algorithms on how to make inferences on MEs and how to explain the effects are described in Yu et al. [-@Yu2025].  

To use the R package bmabart, we first install the package in R (`install.packages("bmabart")`) and load it. 

```{r,echo=T,results='hide'}
library(bmabart)
```

## Data Organization and Transformation
The data_org function is used for read in exposure, IVs, outcomes, and covariates, and transform them into formats needed for BART fitting. The transformation including binarize the categorical variables, and identify the type (e.g. binary, catecorical or continuous) of the input variables, exposure, IVs, outcomes, and covariates for IVs and outcomes separately.  Users don't have to run  ``data_org'' separately. The function ``bma.bart'' will call the function ``data_org'' first for the mediation analysis. The output of the organized data is saved in the ``bma.bart'' object as ``data0''.

##Bayesian Mediation Analysis and Interpretation

### Perform the analysis and summarize the result
We use bma.bart function to make inferences on the ME. And then the summary function helps summarize the estimation results from the bma.bart object. In the following code, the exposure is sex, weight_behavior[,3], the outcome is overweigh (weight_behavior[,15], yes or no), and potential IVs are weight_behavior[,c(2,4:14)]. Since the outcome is binary, we define the reference outcome as 0 (not over-weighted, refy=0). The reference group for the exposure is female (predref=``F''). The number of burn-ins in the MCMC process is 10 (nskip=10) and the number of posterior samples is set at 100 (ndpost=100). In practice, we need to increase the nskip and ndpost of the final model to make sure the convergence of the MCMC process.

```{r,echo=T,results='hide'}
data(weight_behavior)
try0= bma.bart(pred=weight_behavior[,3], m=weight_behavior[,c(2,4:14)], 
               y=weight_behavior[,15], refy = 0, predref = "F",nskip=10,ndpost=100)
summary(try0)
```
```{r,echo=T}
summary(try0)
```
By default, the summary function displays the estimated relative effects using Method 3, the G-computational method. When using method=2, the displayed results will be from the product method: the indirect effects are calculated as the product of the changing rates from the exposure to the mediator, and the changing rate from the mediator to the outcome. ``method=4'' is for G-computation with non-parametric method (binary exposures only).

The relative effects is calculated as the mediation effect divided by the total effect. In general, if the total effect is not significantly different from zero, the relative effect will be very variant since the denominator is a number close to zero. In that scenario, the relative effect is not very meaningful. Use the argument RE=F will give the inference summary for the ME directly.

```{r}
 summary(try0,method=2,RE=F)
```
Interpretation: Using method 2, the above table shows the estimated total effect (TE), direct effect (DE), and indirect effect from each IV between the exposure, sex, and the outcome, overweigh (yes or no). The posterior mean (mean), standard deviation (sd), and quantiles of the posterior distributions are listed in the table. By default, the quantiles are set at quant=c(0.025, 0.25, 0.5, 0.75,0.975). The list can be changed at the summary function using the quant argument.

In addition, the figure shows the estimates with the bars indicate the credible sets of the corresponding estimates. One can set plot=FALSE, if the figure is not needed.

### Perform BMA with BART adding covariates
Covariates for outcomes are variables that can explain the outcomes but not relate to the exposure variable. We can include covarites for outcomes in the analysis by adding the argument cova. In the following codes, ageis used as a covariate for exploring the gender differences in bmi.
```{r,echo=T,results='hide'}
try1= bma.bart(pred=weight_behavior[,3], m=weight_behavior[,c(5:12)], 
               cova=weight_behavior[,2], y=weight_behavior[,1], 
               refy = 0, predref = "F",nskip=10,ndpost=20)
summary(try1)
```

Another sets of covariates can be used for mediators, which is set by the arguments mcov and mclist. The mcov is teh covariance data for mediators. If mclist is null but not mcov, mcov is applied to all mediators. If both mcov and mclist are not NULL, the first item of mclist lists all mediators that are using different mcov, the following items gives the mcov for the mediators in order, NA if no mcov to be used. In the following example, there are 8 IVs, weight_behavior[,c(5:12)]. By setting mclist=c(list(var=1:7),rep(NA,6),list(1)), IVs 1 to 6 have no covariates, IV 7 has only one covariates, weight_behavior[,13] and IV 8 has all covariates in mcov.

```{r, echo=T, results='hide'} 
try2= bma.bart(pred=weight_behavior[,3], m=weight_behavior[,c(5:12)], 
               cova=weight_behavior[,2], mcov=weight_behavior[,13:14], 
               mclist=c(list(var=1:7),rep(NA,6),list(1)),
               y=weight_behavior[,1], refy = 0, predref = "F",nskip=0,ndpost=2)
```
```{r, fig.show='hold'} 
summary(try2)
```

### Multiple Predictors
Multiple predictors can be included. The mediation effects will be shown for each pair of the predictor-outcome relationship. Note that a k-category predictor is decomposed into  k-1 binarized dummy predictors. The same is done for categorical outcomes. Besides that, multiple outcomes are not allowed currently. User has to perform a separate analysis for each outcome.

```{r, echo=T, results='hide'}
try3= bma.bart(pred=weight_behavior[,c(1,4)], m=weight_behavior[,c(2:3,5:14)], 
               y=weight_behavior[,15], refy = 0, predref = "OTHER",nskip=0,ndpost=2)
```
```{r}
summary(try3)
```

## Using the outputs of bma.bart
The bma.bart function returns a bma.bart object. There are many other information can be used. Using try0 as an example, the following codes showed some use of the results.

###Show DIC and related paramters
```{r}
 try0$DIC$D_bar
 try0$DIC$var_D
 try0$DIC$p_D #calculated using two methods
 try0$DIC$DIC
```
Besides that the deviance for the outcome and each mediator is saved in deviances.y and deviances.m separately.

###The fitted models, and a-part and b-part in method 2
The fitted BART for the outcome is saved as y.model, and that for each IV is saved in m.models. 

For method 2, there are two outputs: a-part and b-part. a-part shows the changing rate of the corresponding IV with the predictor, and b-part the changing rate of the outcome with each IV.

The following simulation shows a way to use these outputs.

```{r, results='hide'}
#generating the data
set.seed(123)
n <- 1000
X <- rnorm(n)
M <- 0.5 + 0.5 * X^2 + rnorm(n)     
Y <- 0.6 * M^3 + 0.5* X + rnorm(n)  

data <- data.frame(X = X, M = M, Y = Y)
try4= bma.bart(pred=X, m=M, y=Y, ndpost=10L, nskip=100L)  #use the sd/10 for X and M
summary(try4)

```

```{r}
summary(try4)
#Associations between X and M
plot(X, M, main = "BART Model: X vs M", ylab = "M", xlab = "", pch = 16, col = "blue") 
points(X, try4$m.models[[1]]$yhat.train.mean, col = "red", pch = 16)

ie2.apart=try4$apart.ie[,,1]  
plot(X,apply(ie2.apart,2,mean), main = "X vs apart", ylab = "apart",xlab = "", pch = 16, col = "red") 
#Association between M and Y
plot(M, Y, main = "BART Model: M vs Y", ylab = "Y", xlab = "", pch = 16, col = "blue") #
points(M, try4$y.model$yhat.train.mean, col = "red", pch = 16)
legend("topleft", legend = c("Observed", "BART Predictions"), col = c("blue", "red"), 
       pch = c(16,16), bty="n")

ie2.bpart=try4$bpart.ie[,,1]
plot(M, apply(ie2.bpart,2,mean), main = "M vs bpart", ylab = "bpart", xlab = "", col = "red", pch = 16) 
```

## References


