Skip to main content

Framework: what exactly covaries?

Question. When two traits are measured on the same occasion, do their deviations reflect stable differences among individuals, shared short-term variation, or both?

Intuition before algebra

A behavioural syndrome is a pattern of associations among individuals across behaviours. If consistently exploratory animals are also more aggressive, the two behaviours may matter together for how animals find resources or interact with rivals. Within an animal, exploration and aggression might instead change together as conditions change, such as when a rival appears. These patterns can guide questions about trade-offs and selection. The correlations alone cannot tell us what causes the association, whether it improves fitness, or whether the behaviours share a genetic basis.

We call each repeated measurement period an occasion. An occasion is a trial for the charr and a study year for the dogs.

The two correlations answer different questions and can have opposite signs. A positive between-individual correlation says individuals that are persistently high on one trait tend also to be persistently high on another. A positive within-individual correlation says that, on occasions when an individual is high relative to its own expectation on one trait, it tends to be high on the other. One does not imply the other.

WarningDo not pool levels

A correlation calculated after ignoring repeated measures mixes stable differences among individuals with changes across occasions within individuals. It does not answer either level-specific question.

See the distinction

The following deliberately constructed example has five individuals, each measured five times. Individuals with higher average values of trait A also have higher averages of trait B. Within each individual, however, higher-than-usual A accompanies lower-than-usual B. The two questions therefore have different answers.

Three labelled scatterplots show the same five constructed individuals. Each individual has a distinct colour and point shape, as identified in the legend. Their means rise together in the middle panel, while their within-individual deviations slope downward in the right panel.
Figure 1: Three views of the same constructed dataset. The first shows repeated scores; the second shows the five individual means; the third removes each individual mean. Between-individual association is positive, while within-individual association is negative.

These constructed observations teach the distinction; they are not evidence about animals or model performance. With finite or uneven replication, correlations of sample means and demeaned observations are not substitutes for estimating the two covariance matrices in a repeated-measures model.

TipA reader’s route through the model

First ask whether the question concerns persistent differences among individuals (B) or deviations within an individual at an occasion (W). Then read the total covariance at that level. Only after that ask whether the selected rank explains much of a trait’s variance (communality) or whether B accounts for much of the trait’s variation across both levels (repeatability). The empirical chapters follow this order before showing package code.

All code for this teaching figure
#!/usr/bin/env Rscript
# Deterministic teaching data: this is not an empirical result or a simulation study.
library(ggplot2)
offset_x <- c(-0.6, -0.3, 0, 0.3, 0.6)
offset_y <- c(0.3, 0.6, -0.2, 0.1, -0.8)
centres <- data.frame(individual = factor(paste0("ID ", 1:5)),
                      x_mean = 1:5,
                      y_mean = c(1.3, 1.7, 3.0, 3.5, 4.4))
observations <- centres[rep(seq_len(nrow(centres)), each = 5), ]
observations$x <- observations$x_mean + rep(offset_x, 5) *
  (1 + 0.1 * as.integer(observations$individual))
observations$y <- observations$y_mean + rep(offset_y, 5) *
  (1 + 0.08 * as.integer(observations$individual))
panels <- rbind(
  data.frame(individual = observations$individual, x = observations$x,
             y = observations$y, panel = "Observed scores"),
  data.frame(individual = centres$individual, x = centres$x_mean,
             y = centres$y_mean, panel = "Differences among individuals"),
  data.frame(individual = observations$individual,
             x = observations$x - observations$x_mean,
             y = observations$y - observations$y_mean,
             panel = "Deviations within individuals")
)
panels$panel <- factor(panels$panel, levels = c("Observed scores",
  "Differences among individuals", "Deviations within individuals"))
p <- ggplot(panels, aes(x, y, colour = individual)) +
  geom_point(aes(shape = individual), size = 2.7, alpha = 0.85) +
  facet_wrap(~ panel, scales = "free", nrow = 1) +
  scale_colour_brewer(palette = "Dark2", name = "Individual") +
  scale_shape_discrete(name = "Individual") +
  labs(x = "Trait A: score or deviation", y = "Trait B: score or deviation") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom", panel.grid.minor = element_blank(),
        strip.text = element_text(face = "bold"))
dir.create("tutorial/figures", showWarnings = FALSE, recursive = TRUE)
ggsave("tutorial/figures/two-level-teaching.png", p, width = 10.8,
       height = 4.1, dpi = 180)
ggsave("tutorial/figures/two-level-teaching.pdf", p, width = 10.8,
       height = 4.1)

Download the complete figure script.

Read the notation before the equation

The table is a translation key, not extra mathematics. In the two main examples, an individual is one fish or one dog; an occasion is one charr trial or one annual dog record. Red knots appear in a linked extension, where an occasion is a study period (year × replicate).

At a narrow screen width, scroll the table horizontally to read the biological examples in the last column. The table region can receive keyboard focus.

Symbol Read it as Biological example
\(i\), \(j\), \(t\), \(p\) individual, occasion, trait, and measured covariate dog 18, its third annual assessment, chasing, and study year
\(y_{ijt}\) observed value of trait \(t\) that dog’s chasing score in that year
\(\mu_t\), \(x_{ijp}\), \(\beta_{tp}\) trait mean, covariate value, and trait-specific covariate coefficient the expected chasing score after its fitted year adjustment
\(u_{it}\) and \(\mathbf{u}_i\) stable between-individual deviation for trait \(t\), and the vector of all such deviations a dog persistently more chase-prone than expected, considered with its other scores
\(e_{ijt}\) and \(\mathbf{e}_{ij}\) total within-individual, occasion-level deviation for trait \(t\), and its trait vector a particular year when that dog is more chase-prone than its own expected score
\(\boldsymbol{\Sigma}_B\), \(\boldsymbol{\Sigma}_W\) covariance matrices for stable between-individual (B) and within-individual/occasion (W) variation the two matrices later displayed as B and W heatmaps
\(\lambda_{B,tk}\), \(\lambda_{W,t\ell}\), \(z_{B,ik}\), \(z_{W,ij\ell}\) loadings and latent scores for the shared B and W axes how chasing contributes to, and an observation scores on, a fitted shared axis
\(s_{B,it}\), \(s_{W,ijt}\); \(\boldsymbol{\Psi}_B\), \(\boldsymbol{\Psi}_W\) trait-specific deviations, and their diagonal unique-variance matrices chasing variation that the shared axes do not represent

Bold symbols collect several trait-specific values into vectors or matrices. The B and W subscripts label the between- and within-individual levels; they do not name an additional predictor or response.

\(\mathcal{MVN}(\mathbf{0},\boldsymbol{\Sigma})\) means a multivariate normal distribution centred at zero with covariance matrix \(\boldsymbol{\Sigma}\). With that notation, we can write the Gaussian model as

On a narrow screen, press Tab until the equation has a visible outline, then use the arrow keys to scroll across it.

\[ y_{ijt} = \mu_t + \sum_{p=1}^{P}\beta_{tp}x_{ijp} + u_{it} + e_{ijt}, \qquad \mathbf{u}_i \sim \mathcal{MVN}(\mathbf{0},\boldsymbol{\Sigma}_B),\quad \mathbf{e}_{ij} \sim \mathcal{MVN}(\mathbf{0},\boldsymbol{\Sigma}_W). \tag{1}\]

The fixed part, \(\mu_t+\sum_{p=1}^{P}\beta_{tp}x_{ijp}\), handles designed or measured predictors. The between-individual matrix \(\boldsymbol{\Sigma}_B\) says how stable individual deviations co-vary. The within-individual matrix \(\boldsymbol{\Sigma}_W\) says how deviations around an individual’s expected value co-vary on the same occasion. Here \(e_{ijt}\) is the complete within-individual deviation, including short-term state and measurement variation; there is no additional residual covariance term in this specification. The symbols \(s_{B,it}\) and \(s_{W,ijt}\) are reserved below for the trait-specific parts of the reduced-rank decomposition. The level-specific matrices \(\boldsymbol{\Psi}_B\) and \(\boldsymbol{\Psi}_W\) denote their variances.

Real datasets need not contain every trait in every period. The six-trait red-knot example has 464 periods from 58 birds. BMR is missing in 77 periods, including 71 of the 232 periods recorded in year 0. The model keeps every other response observed in those periods; it does not require a complete six-trait record. A missing BMR value contributes no direct BMR information. The model neither imputes it nor models the process that made BMR unavailable. Because most missing BMR values occur in year 0, read associations involving BMR with that pattern in mind. Prepare data shows the response counts and data rule.

The broader response-matrix perspective is developed in Nakagawa et al. (2026), Choosing the Response Matrix: Generalised Linear Latent Variable Models for Multivariate Ecology and Evolution (EcoEvoRxiv preprint). Choosing rows as individuals and columns as traits defines the biological association of interest. Repeated records then allow us to ask how that association separates into between-individual and within-individual components.

Read a covariance matrix like a biological table

The diagonal contains each trait’s variance: how widely its values vary at this level. An off-diagonal cell contains covariance: whether two traits tend to deviate in the same direction (positive) or in opposite directions (negative). Covariance retains the traits’ measurement units.

A correlation divides covariance by the two standard deviations, placing it on a scale from \(-1\) to \(1\). For traits \(t\) and \(m\) at the between-individual level,

\[ r_{B,tm}=\frac{(\boldsymbol{\Sigma}_B)_{tm}} {\sigma_{B,t}\sigma_{B,m}}. \]

The within-individual analogue is \(r_{W,tm}=(\boldsymbol{\Sigma}_W)_{tm}/(\sigma_{W,t}\sigma_{W,m})\). For example, variances of 4 and 9 and covariance of 3 give a correlation of \(3/\sqrt{4\times9}=0.5\). These are constructed numbers, simply to show the calculation. Apply \(r_{B,tm}\) to describe differences among animals, and \(r_{W,tm}\) to describe deviations within an animal. Neither correlation establishes a causal effect of one trait on the other.

A low-rank representation

When many traits are measured, \(\boldsymbol{\Lambda}_B\) and \(\boldsymbol{\Lambda}_W\) are tables of trait loadings on shared B and W axes, and \(\boldsymbol{\Psi}_B\) and \(\boldsymbol{\Psi}_W\) (uppercase Greek psi) are diagonal matrices of the remaining trait-specific variances. Their off-diagonal entries are zero, so each unique part adds variance to a trait without adding covariance between traits. A loading tells us how strongly a trait varies along an axis; it is not a correlation by itself. The superscript \(\mathsf{T}\) means transpose: swap the rows and columns before multiplying. We write the two decompositions as

\[ \boldsymbol{\Sigma}_B = \boldsymbol{\Lambda}_B\boldsymbol{\Lambda}_B^\mathsf{T} + \boldsymbol{\Psi}_B, \qquad \boldsymbol{\Sigma}_W = \boldsymbol{\Lambda}_W\boldsymbol{\Lambda}_W^\mathsf{T} + \boldsymbol{\Psi}_W. \]

Equivalently, at the trait level,

\[ u_{it}=\sum_{k=1}^{d_B}\lambda_{B,tk}z_{B,ik}+s_{B,it}, \qquad e_{ijt}=\sum_{\ell=1}^{d_W}\lambda_{W,t\ell}z_{W,ij\ell}+s_{W,ijt}. \]

For example, chasing can share variation with other traits among dogs while having a different amount of shared variation across years within a dog. The rank is the number of shared axes. A rank is a modelling choice, not a discovered number of biological mechanisms.

The Ordination lesson shows how to display this selected shared structure without confusing a latent-axis picture with the complete covariance matrix or with a biological mechanism.

One covariance target, two ways to write it

Readers need to distinguish the scientific target from the package syntax. For an ordinary Gaussian two-level model with rank one, the target at each level is the same:

\[ \boldsymbol{\Sigma}=\boldsymbol{\Lambda}\boldsymbol{\Lambda}^{\mathsf T} +\boldsymbol{\Psi}. \]

gllvmTMB (Nakagawa 2026) writes that target in one latent() term. Its ordinary default is unique = TRUE; the tutorials state that argument explicitly so that readers can see that the trait-specific diagonal \(\boldsymbol{\Psi}\) is part of the model:

latent(0 + trait | individual, d = 1, unique = TRUE)

glmmTMB (Brooks et al. 2017; McGillycuddy et al. 2025) separates the same two pieces. rr() supplies the shared \(\boldsymbol{\Lambda}\boldsymbol{\Lambda}^{\mathsf T}\) term. At each level, the model also needs one declared source of the trait-specific diagonal \(\boldsymbol{\Psi}\). The usual construction places it in diag():

rr(0 + trait | individual, d = 1) +
  diag(0 + trait | individual)

Writing rr() alone removes the trait-specific component; it is therefore a different covariance model. Conversely, latent(..., unique = FALSE) requests the corresponding loadings-only subset in gllvmTMB.

In the Gaussian fits used here, glmmTMB places the shared axes in rr(). The between-individual trait-specific variances are supplied by diag(). At the within-individual level, they are supplied by dispformula = ~ 0 + trait, so we do not add a second W-level diag() term. gllvmTMB puts the shared and trait-specific parts together in each latent(..., unique = TRUE) term. The rank-one calls above illustrate this notation; the tutorial fits use two axes at each level for charr and red knots, and three at each level for dogs. The complete calls appear beside each example. We compare the reconstructed \(\boldsymbol{\Sigma}_B\) and \(\boldsymbol{\Sigma}_W\) after aligning the observations, mean model, grouping keys, ranks, and residual convention. The loading signs themselves are arbitrary.

For trait \(t\), communality at one level is the fraction of its total variance represented by the shared part. The subscript tt selects trait \(t\)’s diagonal variance from a matrix:

\[ c_{B,t}^2 = \frac{\left[\boldsymbol{\Lambda}_B\boldsymbol{\Lambda}_B^\mathsf{T}\right]_{tt}} {\left[\boldsymbol{\Sigma}_B\right]_{tt}}, \qquad \psi_{B,t} = \frac{\left[\boldsymbol{\Psi}_B\right]_{tt}} {\left[\boldsymbol{\Sigma}_B\right]_{tt}} = 1-c_{B,t}^2. \]

The W-level definitions, \(c_{W,t}^2\) and \(\psi_{W,t}\), replace B with W in the same expressions. Lowercase \(\psi_{B,t}\) or \(\psi_{W,t}\) is the unique variance fraction for one trait; uppercase \(\boldsymbol{\Psi}_B\) and \(\boldsymbol{\Psi}_W\) contain the unique variances themselves. If a trait’s total variance at one level is 10, with 6 represented by the shared axes and 4 remaining unique, its communality is \(6/10=0.6\) and its unique variance fraction is \(4/10=0.4\). The matrix’s diagonal entry is 4, not 0.4. These constructed numbers illustrate the distinction; both fractions refer to the same trait and the same level of variation.

Communality depends on the chosen level (B or W), rank, trait set and model specification. Consistent linear changes of a trait’s units leave this variance proportion unchanged; nonlinear transformations can change it. A high communality means that the shared axes represent a large proportion of the trait’s variance at that level. It tells us how the trait participates in the measured suite, but does not establish the biological mechanism behind that association.

Repeatability and communality answer different questions

Repeatability asks how much of a trait’s total modelled variance lies between individuals:

For one trait \(t\), \((\boldsymbol{\Sigma}_B)_{tt}\) and \((\boldsymbol{\Sigma}_W)_{tt}\) are the diagonal entries (variances) for that trait in the B and W matrices. Thus the subscript tt means “this trait’s own variance,” not a correlation with another trait.

\[ R_t = \frac{(\boldsymbol{\Sigma}_B)_{tt}} {(\boldsymbol{\Sigma}_B)_{tt}+(\boldsymbol{\Sigma}_W)_{tt}}. \]

Here the variances are conditional on the specified fixed effects. A high repeatability means stable individual differences account for a large share of the remaining variation. It does not say that those differences are shared with other traits.

Communality asks how much variance at a particular level is shared with the measured trait set under the chosen latent representation. For example, the dog chasing score has repeatability about 0.73 but between-dog communality about 0.33 in the ten-score dog example. About a third of the fitted between-dog chasing variance follows the three shared axes, while most of its total fitted variance is between dogs. Conversely, a trait can have high communality at B even if B accounts for little of its total variance.

Read both quantities with their denominator in mind. Repeatability partitions a trait’s variance across levels; communality partitions its variance within one level. Their point estimates and uncertainty also depend on the response scale and model specification. The worked examples calculate both directly from the same covariance matrices.

Phenotypic correlation mixes the two levels

A raw correlation between two traits, measured across all records, is closest to the phenotypic correlation. Conditional on the covariates in the mean model, the phenotypic covariance matrix is the sum of the two levels,

\[ \boldsymbol{\Sigma}_P=\mathrm{Var}(\mathbf{y}_{ij}\mid\mathbf{x}_{ij})=\boldsymbol{\Sigma}_B+\boldsymbol{\Sigma}_W, \qquad \mathbf{C}_P=\mathbf{D}_P^{-1/2}\boldsymbol{\Sigma}_P\mathbf{D}_P^{-1/2}, \qquad \mathbf{D}_P=\mathrm{diag}(\boldsymbol{\Sigma}_P). \]

For traits \(t\) and \(m\), the phenotypic correlation is a weighted sum of the B and W correlations, with weights set by the two repeatabilities:

\[ r_{P,tm}=r_{B,tm}\sqrt{R_tR_m}+r_{W,tm}\sqrt{(1-R_t)(1-R_m)}. \]

This is why a phenotypic correlation cannot tell a behavioural syndrome (\(\mathbf{C}_B\)) from coordinated within-individual variation (\(\mathbf{C}_W\)).

Suppose a trait has total variance 1, split evenly between individuals and within individuals. The B and W variances are each 0.5, so \(R=0.5\). The B variance splits into shared variance 0.35 and unique variance 0.15, giving \(c_B^2=0.35/0.5=0.7\). The W variance splits into 0.20 and 0.30, giving \(c_W^2=0.20/0.5=0.4\).

Now take two such traits, each with \(R=0.5\). Suppose, for illustration only, that \(r_B=0.6\) and \(r_W=-0.2\). Both weights are 0.5, so \(r_P=0.6(0.5)+(-0.2)(0.5)=0.2\). A modest positive phenotypic correlation hides a strong positive B correlation and a negative W correlation. The weights need not sum to one. If \(R_t=0.8\) and \(R_m=0.2\), both weights are \(\sqrt{0.16}=0.4\), and the same \(r_B\) and \(r_W\) give \(r_P=0.16\). In general, the weights satisfy

\[ \sqrt{R_tR_m}+\sqrt{(1-R_t)(1-R_m)}\le 1, \]

with equality only when \(R_t=R_m\).

These values illustrate the algebra and are not empirical estimates. With covariates in the mean model, a raw pooled correlation also contains variation explained by those covariates, so it need not equal \(\mathbf{C}_P\).

TipReader checkpoint: three related quantities, three questions
  • A B correlation asks whether dogs that are persistently high on one score also tend to be persistently high on another score. A W correlation asks whether a dog departs from its own expected scores on both traits together in a particular year.
  • Repeatability is about one score across B and W. For chasing, \(R=0.728\) says that most fitted chasing variation is between dogs after the stated year adjustment.
  • B communality is about one score within B. For the same chasing score, \(c_B^2=0.330\) says that about a third of its between-dog variance follows the shared axes in the ten-score dog model.

These statements can all be true at once. Before reading the dog results, identify the denominator: B plus W for repeatability; B alone for B communality; two traits at one level for a correlation.

One-realisation teaching simulation outline

The following is a single, deterministic illustration of the B/W decomposition. It is deliberately not a performance, sample-size, or coverage study: one simulated realisation cannot show how reliably an estimator works. It uses base R only and is provided so a reader can change the B or W covariance and see which pattern changes.

# Guidance only. This code did not run during this render; it creates one constructed realisation, not evidence.
set.seed(20260907)
n_individual <- 80L
n_occasions <- 6L
Sigma_B <- matrix(c(1, 0.7, 0.7, 1), 2)
Sigma_W <- matrix(c(1, -0.4, -0.4, 1), 2)
draw_normal <- function(n, Sigma) {
  matrix(rnorm(n * ncol(Sigma)), n) %*% chol(Sigma)
}
u <- draw_normal(n_individual, Sigma_B)
e <- draw_normal(n_individual * n_occasions, Sigma_W)
individual <- rep(seq_len(n_individual), each = n_occasions)
y <- u[individual, , drop = FALSE] + e
# Compare covariance of individual means with covariance of y minus those means.

The names deliberately match the framework: u creates stable among-individual deviations and e creates occasion-level deviations. Changing a covariance changes this one picture, not a performance claim about either package.

TipReader checkpoint: use the charr figure

Open the six-panel charr figure. Find distance and exit time in panels A and B. Which panel compares fish, and which compares trials within fish? Then follow distance to panel E for communality at each level and panel F for repeatability. What is in the denominator each time?

Package translation

For stacked Gaussian data, reduced-rank random-effect terms express a low-rank covariance component. The formula must identify the trait factor, the individual grouping factor, and the observation-level grouping factor. All candidates need the same rows and fixed-effect design before their information criteria can be compared.

gllvmTMB::gllvmTMB() uses an explicit unit for the between-unit level and unit_obs for the within-unit level. Its ordinary latent() term defaults to unique = TRUE, which decomposes a covariance source into a shared low-rank part and a trait-specific companion. The paired lessons write that default explicitly and compare the reconstructed matrices with the glmmTMB rr() + diag() construction, rather than comparing loading signs.

How to use the code. The paired chapters show the public API calls used for the recorded analyses and the retained output. The empirical fits are rerun with the analysis scripts, not by the site’s diagnostic-summary chunks. Other code examples say clearly when they are guidance only and did not run in this render; they show a workflow without claiming an empirical result.

References

Brooks, Mollie E., Kasper Kristensen, Koen J. Van Benthem, et al. 2017. “glmmTMB Balances Speed and Flexibility Among Packages for Zero-Inflated Generalized Linear Mixed Modeling.” The R Journal 9 (2): 378–400. https://doi.org/10.32614/RJ-2017-066.
McGillycuddy, Maeve, Gordana Popovic, Benjamin M. Bolker, and David I. Warton. 2025. “Parsimoniously Fitting Large Multivariate Random Effects in glmmTMB.” Journal of Statistical Software 112 (1): 1–19. https://doi.org/10.18637/jss.v112.i01.
Nakagawa, Shinichi. 2026. gllvmTMB: Fit Multivariate Models from Wide Response Data. https://itchyshin.github.io/gllvmTMB/authors.html#citation.