Converts MCMC samples from a hierarchical Bayesian model into a tidy (long-format) `data.frame` enriched with taxonomic information. The function identifies the level (species, complex, or genus), assigns names based on taxonomy, and maps groupings for later plotting.

prepare_data_density(stan_results)

Arguments

samples

An object of class `mcmc.list` (e.g., output from `coda::mcmc.list`), containing posterior samples for species- and complex-level parameters (named `p1[...]` and `p2[...]`).

chain_length

Integer. Total number of MCMC iterations per chain.

burnin

Integer. Number of initial iterations to discard as burn-in.

thinning

Integer. Thinning interval used during sampling (e.g., every 10th draw).

species_complex

A `data.frame` mapping species and complexes. Must include:

  • `species`: species names,

  • `complex`: complex names,

  • `speciesNb`: integer codes for species (matching Stan),

  • `complexNb`: integer codes for complexes (matching Stan).

Value

A `data.frame` in long format with the following columns:

`value`

Posterior sample value.

`Nb`

Index number of the parameter (species or complex ID).

`level`

Level of the parameter: `"species"`, `"complex"`, or `"genus"`.

`name`

Name of the species, complex, or `"GENUS"` (for group-level effect).

`higher_level`

Grouping label: complex name for species, self-name for complex/genus.

Details

Species-level parameters are assumed to be named `p2[...]` and complex-level parameters `p1[...]`. A special case is handled when `p1[1]` represents the genus-level intercept. The function processes indices and variable names using regular expressions, and joins taxonomic metadata using `species_complex`.