---
title: "Mixed-Model"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Mixed-Model}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

has_cmdstan <- instantiate::stan_cmdstan_exists()
```

```{r setup}
library(bvarnet)
library(qgraph)
```

## Mixed-family VAR

`bvarnet` allows combining different outcome families in a single VAR model
by passing a named vector to the `family` argument. This is useful when the
variables in the network are measured on different scales.

In this example we fit a mixed-family VAR(1) with three types of outcome:

- **ordinal**: `stress_level` (5-point Likert items)
- **binary**: `happyornot_bin` (binarised daily average)
- **gaussian**: `sleep_duration` (hours)

## Load Data
Again, we start with loading the data
```{r}
data(studentlife)
```


### Priors

For a mixed-family model we specify priors for all parameter types that can appear. Here that means we need to specify priors for the following parameters: `intercept`, `phi` (temporal), `beta` (fixed effects), `kappa` (ordinal thresholds), and `sigma` (gaussian residual SD).

```{r}
priors <- set_priors(
  intercept = prior(family = "normal", loc = 0, scale = 1),
  phi = prior(family = "normal", loc = 0, scale = 0.5),
  beta = prior(family = "normal", loc = 0, scale = 1),
  kappa = prior(family = "normal", loc = 0, scale = 1),
  sigma = prior(family = "normal", loc = 0, scale = 1)
)
```

### Estimation

We pass a named character vector to `family` so that each outcome gets the
appropriate likelihood.

```{r, eval = has_cmdstan, results='hide', message=FALSE}
fit_mixed <- bvar(
  id_col   = "id",
  time_col = "day",
  y_cols   = c("stress_level", "happyornot", "sleep_duration"),
  x_cols   = NULL,
  re_cols  = NULL,
  re_temporal = FALSE,
  K        = 1,
  data     = studentlife,
  family   = c(stress_level = "ordinal",
               happyornot = "bernoulli",
               sleep_duration = "gaussian"),
  priors   = priors,
  iter     = 4000,
  warmup   = 2000,
  chains   = 4,
  cores    = 4,
  seed     = 1337
)
```

### Results

```{r, eval = has_cmdstan}
print(fit_mixed)
```

```{r, eval = has_cmdstan}
summary(fit_mixed)
```

The temporal network can be extracted and inspected as usual:

```{r plot-network-mixed, eval = has_cmdstan}
nw_mat <- extract_network_matrix(fit_mixed)
qgraph(nw_mat)
```

As every other model, the mixed model can be extended by random effects (`Vignette(Random-Effects)`), hypothesis tests can be performed (`Vignette(Hypothesis-Testing)`).
