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

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

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

## Setup

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

## Data

```{r}
data(studentlife)
```

There is some missing data in the dataset. The models default options handle this by themselves. For a further elaboration on this, you can read `vignette("Missing-Data")`.

## Random-Effects Arguments

For the following tutorial we will extend the network containing the the variables `anxious`, `calm`, `conventional`, `critical`, and `dependable` from the `Vignette(bvarnet)`. To introduce a multilevel structure to our model, we can use the two arguments: `re_cols` and `re_temporal`.

The `re_cols` argument accepts all variables that we specify in `x_cols` and `"Intercept"`, to introduce random effects on the baseline model.
The `re_temporal` argument is a binary TRUE/FALSE indicator to introduce random effects on the temporal structure.

## Model Estimation

To estimate a model with random effects, we can use the following code, where we specify the `re_cols = c("Intercept")` to introduce random effects on the baseline model, and `re_temporal = TRUE` to introduce random effects on the temporal structure:
```{r, eval = has_cmdstan, results='hide', message=FALSE}
fit <- bvar(
  id_col = "id",
  time_col = "day",
  y_cols = c("anxious", "calm", "conventional", "critical", "dependable"),
  x_cols = NULL,
  re_cols = c("Intercept"),
  re_temporal = TRUE,
  K = 1,
  data = studentlife,
  family = c("ordinal"),
  iter = 4000,
  warmup = 1000,
  chains = 4,
  cores = 4,
  seed = 1337
)
```

## Model Output

```{r, eval = has_cmdstan}
print(fit)
summary(fit)
```

## Extracting Random Effects

Additionally to the `extract_*` functions that we already described in `Vignette(bvarnet)`, we can use the `extract_random_effects()` function to only extract the random effects:
```{r, eval = has_cmdstan}
re <- extract_random_effects(fit)
re
```

