---
title: "MARS Model Examples"
author: "Brandon LeBeau"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{MARS Model Examples}
  \usepackage[utf8]{inputenc}
  %\VignetteEngine{knitr::rmarkdown}
editor_options:
  chunk_output_type: console
---

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

This vignette shows three common ways to use `mars()`:

1. a univariate meta-analysis with one effect size per study,
2. a multivariate meta-analysis with multiple dependent effect sizes, and
3. a multilevel meta-analysis with nested effect sizes.

The examples use datasets included with the package and keep the fitted models
small enough to run quickly during package installation.

```{r package}
library(mars)
```

## Selecting Coefficient Inference

`summary(fit)` keeps the default output, including stored robust results when
available. Explicit `inference` and `test` arguments select one coefficient
table and report its covariance method, reference distribution, degrees of
freedom, and confidence intervals. These choices apply to the summary; they
preserve the fitted estimates, heterogeneity, and original model object.

| Model | Model-based tests | Cluster-robust tests |
|---|---|---|
| Independent univariate | `"z"`, `"t"`, `"hksj"`, `"Satterthwaite"` | `"z"`, `"naive-t"`, `"naive-tp"`, `"Satterthwaite"` |
| Multivariate/correlation synthesis | `"z"`, `"Satterthwaite"` | Same robust choices, clustering by independent study |
| Multilevel | `"z"`, `"Satterthwaite"` | Same robust choices, clustering above dependent effects |

Model-based Satterthwaite requires a converged fit with estimated, interior,
identifiable heterogeneity and GLS covariance. HKSJ requires independent
univariate ML/REML data with estimated constant heterogeneity and inverse-variance
GLS weights. Robust choices require independent clusters, an estimable covariance
adjustment, and positive degrees of freedom. See `?mars_inference_options` for
the full compatibility table and argument combinations.

## Univariate Meta-Analysis

Use `structure = "univariate"` when each row contributes a single effect size
with its own sampling variance. The `bcg` data include log risk-ratio estimates
(`yi`) and their sampling variances (`vi`) from tuberculosis vaccine trials.

```{r univariate-fit}
fit_uni <- mars(
  data = bcg,
  formula = yi ~ 1,
  studyID = "trial",
  variance = "vi",
  varcov_type = "univariate",
  structure = "univariate",
  estimation_method = "MLE"
)

summary(fit_uni)
```

Moderators can be added directly to the formula. Here, absolute latitude is used
as a study-level predictor.

```{r univariate-moderator}
fit_uni_mod <- mars(
  data = bcg,
  formula = yi ~ 1 + ablat,
  studyID = "trial",
  variance = "vi",
  varcov_type = "univariate",
  structure = "univariate",
  estimation_method = "MLE"
)

summary(fit_uni_mod)
```

### Normal, t, and Hartung-Knapp inference

Use `inference = "model"` to select model covariance. Normal Wald inference uses
`test = "z"`. The residual-df t test uses the same covariance with `n - p` degrees
of freedom, where `n` is the number of independent effects and `p` is the number
of mean coefficients. `level` sets pointwise coefficient confidence coverage.

```{r univariate-wald-inference}
summary(fit_uni_mod, inference = "model", test = "z", level = 0.90)
summary(fit_uni_mod, inference = "model", test = "t", level = 0.90)
```

Hartung-Knapp (`"hksj"`, also accepted as `"knha"`) rescales coefficient covariance
by the weighted residual sum of squares divided by `n - p` and uses a t
distribution. The modified adjustment bounds that scale below by one, so it
cannot reduce the GLS standard errors.

```{r univariate-hksj-inference}
summary(fit_uni_mod, inference = "model", test = "hksj",
        hksj_adjust = "standard")
summary(fit_uni_mod, inference = "model", test = "hksj",
        hksj_adjust = "modified")

# Use the same settings to extract matching coefficient intervals.
confint(fit_uni_mod, inference = "model", test = "hksj",
        hksj_adjust = "modified")
```

Model-based Satterthwaite instead uses expected covariance-parameter information
to approximate coefficient-specific degrees of freedom, retaining GLS standard
errors. This differs from the cluster-robust Satterthwaite calculation below.

```{r univariate-satterthwaite-inference}
summary(fit_uni_mod, inference = "model", test = "Satterthwaite")
```

## Multivariate Meta-Analysis

Use `effectsize_type = "cor"` for correlations stored in a wide study-level
dataset. In this workflow, `variable_names` identifies the correlation columns,
and `mars()` builds the working multivariate dataset internally.

```{r multivariate-fit}
fit_mv <- mars(
  data = becker09,
  studyID = "ID",
  effectID = "numID",
  sample_size = "N",
  effectsize_type = "cor",
  varcov_type = "weighted",
  variable_names = c(
    "Cognitive_Performance",
    "Somatic_Performance",
    "Selfconfidence_Performance",
    "Somatic_Cognitive",
    "Selfconfidence_Cognitive",
    "Selfconfidence_Somatic"
  )
)

summary(fit_mv)
```

The result estimates the average correlation vector and a between-study
covariance structure for the dependent correlations.

### Cluster-robust inference for pooled correlations

Supply `cluster` as the name of the column identifying independent studies in
the fitted analysis data. Correlation synthesis reshapes the input and stores
that column name in `fit_mv$study_id` (`"study"` here), keeping each study's
dependent correlations together. `robust_type`
selects the sandwich covariance adjustment; `"CR2"` with
`test = "Satterthwaite"` uses cluster influences for coefficient-specific degrees
of freedom. If a fit already stores robust clustering, `cluster` can be omitted.

```{r multivariate-robust-inference}
summary(fit_mv, inference = "robust", cluster = fit_mv$study_id,
        robust_type = "CR2", test = "Satterthwaite")
```

These options apply to the pooled correlation coefficients. A subsequent path
or factor model has its own summary and does not inherit these test choices.
HKSJ and residual-df model t tests are unavailable for dependent correlations.

## Multilevel Meta-Analysis

Use `structure = "multilevel"` when effect sizes are nested. Random effects are
specified in the model formula with the same general style as mixed-model
formulas. In the `school` data, effects are nested within studies, and studies
are nested within districts.

```{r multilevel-fit}
fit_ml <- mars(
  data = school,
  formula = effect ~ 1 + (1 | district/study),
  studyID = "district",
  variance = "var",
  varcov_type = "multilevel",
  structure = "multilevel",
  estimation_method = "MLE"
)

summary(fit_ml)
```

Fixed moderators can be combined with the random-effects structure in the same
formula.

```{r multilevel-moderator}
fit_ml_mod <- mars(
  data = school,
  formula = effect ~ 1 + year + (1 | district/study),
  studyID = "district",
  variance = "var",
  varcov_type = "multilevel",
  structure = "multilevel",
  estimation_method = "MLE"
)

summary(fit_ml_mod)
```

### Model-based and robust Satterthwaite inference

For an eligible multilevel fit, model-based Satterthwaite uses the fitted
covariance structure to approximate degrees of freedom. Robust inference instead
uses independent clusters. In these data, districts contain the dependent studies
and effects, so `cluster = "district"` preserves the full dependence blocks.

```{r multilevel-inference}
summary(fit_ml, inference = "model", test = "Satterthwaite")
summary(fit_ml_mod, inference = "robust", cluster = "district",
        robust_type = "CR2", test = "Satterthwaite", level = 0.90)
```

Other robust covariance choices are `"CR0"`, `"CR1"`, `"CR1p"`, `"CR1S"`, and
`"CR3"`. Robust `test = "naive-t"` uses clusters minus one degrees of freedom;
`"naive-tp"` uses clusters minus mean coefficients. Robust `"t"` aliases
`"naive-t"`. Do not split a dependent district into smaller clusters or combine
robust inference with `hksj_adjust` or `vcov_method`.

## Choosing a Structure

The same entry point, `mars()`, handles each model family. The main choice is how
the effect sizes are organized:

* `structure = "univariate"` for one effect size per independent study unit,
* `effectsize_type = "cor"` or `"smd"` for dependent multivariate effect sizes,
* `structure = "multilevel"` for nested effect sizes described with random
  effects in the formula.

After fitting, `summary()` provides the main estimates and standard errors for
each model. Explicit inference choices affect mean-coefficient tests and
pointwise confidence intervals. Heterogeneity and joint model-fit tests,
prediction intervals, and downstream analyses keep their fitted calculations.
Bootstrap, jackknife, and permutation results require their explicit resampling
functions; these are not launched by `summary()`.
