---
title: "Mixed Correlations for Study-Level Path Analysis"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Mixed Correlations for Study-Level Path Analysis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

`mixed_corr_meta()` computes associations across rows of effect sizes and
moderators. This is a study-level analysis, distinct from pooling participant-level
correlation matrices reported by multiple studies. These associations do not
establish participant-level relationships or causal mediation.

## Observed-scale correlations with common weights

```{r data}
set.seed(205)
k <- 120
x <- rnorm(k)
binary <- factor(rep(c("no","yes"),k/2))
ordinal <- ordered(cut(x+rnorm(k),breaks=c(-Inf,-.7,0,.7,Inf),labels=1:4))
d <- data.frame(study=1:k,yi=.3*x+.2*(binary=="yes")+rnorm(k,sd=.4),
  vi=runif(k,.02,.08),x=x,binary=binary,ordinal=ordinal)
mixed <- mixed_corr_meta(d,moderators=c("x","binary","ordinal"),
  bootstrap=250,seed=12,cluster_id="study")
mixed$corr_matrix
mixed$method_matrix
mixed$pair_details
mixed$bootstrap_diagnostics
```

The defaults, `correlation_scale="observed"` and
`weighting="inverse_variance"`, apply the same `1/vi` weights to every pair.
Continuous pairs use weighted Pearson correlations, binary-continuous pairs use
weighted point-biserial correlations and binary pairs use weighted phi.
Ordinal observed-scale correlations use category scores. The coding/order affects
the estimand and should be stated. `effective_n` is a Kish weight diagnostic,
not inferential degrees of freedom.

`weighting="none"` gives equal-weight correlations. `outcome_only` weights only
pairs involving `yi`; this hybrid can produce an indefinite matrix even without
missing data. Differing pairwise missingness can also make a commonly weighted
matrix indefinite. Inspect `min_eigenvalue`; no automatic repair occurs.

## Latent correlations

```{r latent, eval=FALSE}
latent <- mixed_corr_meta(d,moderators=c("x","binary","ordinal"),
  correlation_scale="latent",weighting="inverse_variance",bootstrap=1000,
  cluster_id="study",fallback="error",seed=12)
```

Latent polyserial, polychoric and tetrachoric correlations assume underlying
Gaussian variables separated by ordered thresholds. Weighted marginal proportions
estimate thresholds; a conditional or contingency-table likelihood estimates the
correlation. Bivariate-normal rectangle probabilities are integrated numerically.
The search range is (-.995,.995); boundary estimates fail. No external correlation
package is required.

Latent correlations are not interchangeable with observed-scale correlations.
`fallback="error"` stops on failed latent point estimates; `fallback="observed"`
permits explicitly labelled observed-scale fallback. Sparse categories, category
loss during bootstrap and boundary estimates require investigation. Fallback
can mix estimands, so inspect method labels and bootstrap fallback counts.

## WLS path analysis

```{r path}
fit <- path_model(mixed,"yi ~ x+binary+ordinal")
fit$fit_method
summary(fit)
```

The bootstrap covariance matches the selected correlations. WLS uses it for
fitting and expected-information SEs. This full regression is saturated, so
there is no global fit-test p-value. Existing normal coefficient inference is
pointwise and unadjusted. A study-level `num_obs` does not substitute for the
matched sampling covariance.

```{r resampling}
boot <- path_model(mixed,"yi ~ x+binary+ordinal",se_method="bootstrap",
  se_draws=100,se_seed=14)
boot$se_diagnostics
```

Stored correlation draws remain on the raw-r scale. `use_fisher_z=TRUE` estimates
covariance on Fisher-z scale and back-transforms it with a delta approximation;
FALSE uses empirical raw-r covariance. The adapter contains no between-study
heterogeneity estimate: bootstrap sampling variance is not `Tau`.

## Independent units and uncertainty

If a study supplies several rows, set `cluster_id` to retain those rows together
when resampling studies. Without it, independent rows are assumed. Increasing the
number of bootstrap draws reduces Monte Carlo error, not study dependence.

At least 50 complete draws and an 80 percent success rate are required before
sampling covariance is passed to downstream inference. The inspectable covariance
can still exist when these requirements fail; `bootstrap_diagnostics$sufficient`
explains its usability. Path resampling separately checks admissible model fits.
Specifying a seed preserves the caller's RNG state.

```{r one-moderator}
one <- mixed_corr_meta(d,moderators="x",bootstrap=100,seed=12)
one$varcov_matrix
```

Constant variables, insufficient complete observations and sparse category
support can prevent estimation. Variances must be finite and positive; invalid
values are rejected. A single moderator is supported.
