Skip to main content

Use your own data: from a CSV to a checked first fit

Question. I have repeated measurements of several traits. How do I tell whether this workflow fits my data, prepare a model frame without losing the meaning of my sampling design, and obtain a first checked fit?

This is the practical entry route for your own data. It is deliberately small: it helps you prepare one Gaussian, repeated-trait analysis, fit a rank-one shared-plus-unique model, and obtain a package-supported conditional bootstrap. It does not establish that Gaussian responses, rank one, complete-case retention, or temporal independence are right for your study.

Before you run code

The data audit is suitable when you have identifiable individuals, at least two recorded occasions for some individuals, and at least two traits measured within an occasion that has a defensible biological meaning. The rank-one shared-plus-unique model taught below is a useful first reduced-rank description only with at least four traits: with two or three traits it does not reduce the covariance parameter count, and the shared–unique decomposition is weakly constrained. For two or three traits, start with a simpler bivariate or full multivariate mixed model, or state a separate structural reason for the restriction. An occasion can be a field visit, assay period, experimental replicate, or year; it should not be a convenient row number. If your responses are censored, bounded with substantial boundary values, counts with many zeros, or recorded on different time scales, select a likelihood that represents the observation process and use Diagnostics before fitting a Gaussian model.

Write these five decisions in your analysis record before fitting:

  1. Which traits form the response suite, in what order, and why?
  2. What identifies an individual?
  3. What is one occasion at which trait departures can be considered jointly?
  4. Which predictors belong in the mean model, and do any need separate individual-mean and within-individual-deviation terms?
  5. Is a rank-one shared structure a transparent first description, or is another candidate needed?

Make a checked long data frame

Download the own-data starter and its short guide. It expects a CSV with one row per individual, occasion, and trait measurement. The example below is only a layout; it is not enough data to fit a model.

animal_id visit trait value temperature
bird_01 first boldness 2.3 15
bird_01 first activity 4.1 15
bird_01 first exploration 1.2 15
bird_01 second boldness 2.8 18
# Run in your own analysis folder, after downloading own_data_starter.R.
source("own_data_starter.R")

prepared <- prepare_own_data(
  csv_path = "my_traits.csv",
  individual_col = "animal_id",
  occasion_col = "visit",
  trait_col = "trait",
  value_col = "value",
  traits = c("boldness", "activity", "exploration", "aggression"),
  predictor_cols = "temperature", # use character() when there are no predictors
  missing = "stop",               # make complete-case removal an explicit decision
  standardise = TRUE
)

my_long <- prepared$data
prepared$trait_audit
prepared$repeats
prepared$scaling

The function prints a summary of the input and retained rows. The three tables above answer different questions: trait_audit counts observed and missing values for each trait, repeats counts retained occasions for each animal, and scaling records the number of values, mean and standard deviation used for each trait. Keep these tables beside the fitted model so another reader can see what data the model used and how each response was standardised.

The starter stops on duplicate individual–occasion–trait rows, missing identifiers, non-numeric or infinite responses, constant traits, inconsistent occasion-level predictors, and data without repeat structure. It reports missing trait measurements separately from absent trait rows. It constructs a globally unique occasion key, so a label such as first can recur across individuals without silently combining observations.

Read the printed audit before fitting. For each trait, check observed_values and missing_values. In repeats, check that animals have multiple retained occasions. In scaling, check that each trait has a finite mean and a positive standard deviation. Those values show the transformation used when standardise = TRUE.

If you deliberately choose missing = "complete_occasions", an entire occasion is removed when any selected trait or predictor is missing. That is a transparent complete-case analysis, not a missing-data model. The saved audit and scaling record belong beside your fitted result. If you choose an available-response likelihood instead, state that choice before fitting and follow the red-knot example, which shows how observed traits can remain when one response is missing.

Separate predictor effects before fitting

A predictor such as temperature, food availability or body condition can vary both among animals and across an animal’s visits. A single trait:temperature term combines those two sources of association. Use it only when that combined effect is your stated target. If the biology distinguishes animals that usually experience warmer conditions from a particular warmer-than-usual visit, separate the animal’s average temperature from each visit’s departure from that average. The starter has already checked that an occasion-level predictor has the same value on every trait row from that occasion.

For example, animal A has temperatures of 15 and 17, so its average is 16. Animal B has temperatures of 18 and 20, so its average is 19. The within-animal values show each visit’s difference from that animal’s own average:

temperature_example <- data.frame(
  animal = c("A", "A", "B", "B"),
  temperature = c(15, 17, 18, 20)
)
temperature_example$temperature_between <- ave(
  temperature_example$temperature,
  temperature_example$animal,
  FUN = mean
)
temperature_example$temperature_within <- with(
  temperature_example,
  temperature - temperature_between
)
knitr::kable(
  temperature_example,
  caption = "Averages and within-animal temperature departures in a small example."
)
Averages and within-animal temperature departures in a small example.
animal temperature temperature_between temperature_within
A 15 16 -1
A 17 16 1
B 18 19 -1
B 20 19 1

Here ave() puts each animal’s mean on both of its rows. Subtracting that mean leaves a negative value for a cooler-than-usual visit and a positive value for a warmer-than-usual visit. The reusable function below applies the same calculation to your prepared data. Copy and run this block in your R session; the code is shown but not run when the tutorial is built.

add_within_between <- function(data, predictor, individual = "individual") {
  stopifnot(is.numeric(data[[predictor]]), !anyNA(data[[predictor]]))
  between <- ave(data[[predictor]], data[[individual]], FUN = mean)
  data[[paste0(predictor, "_between")]] <- between
  data[[paste0(predictor, "_within")]] <- data[[predictor]] - between
  data
}

my_long <- add_within_between(my_long, "temperature")

temperature_between compares individuals with different average temperatures. temperature_within compares each visit with that individual’s own average. This changes the mean model, and therefore the covariance described after adjustment. Do not split a predictor merely by default; state which scientific question needs the separation.

Fit a small first model

The next code blocks are for you to copy and run in your own R session. The tutorial build does not execute them because they need your data, so the fitted objects and output will be specific to your analysis.

The first glmmTMB fit below has one shared axis and a trait-specific unique variance at both levels. It uses separate between- and within-individual temperature effects because the preceding example created them. If your question deliberately uses one combined occasion-level effect, replace both terms by trait:temperature; with no predictors, remove them all. Do not add random slopes because they look sophisticated: they answer a different question.

library(glmmTMB)

fit_glmm <- glmmTMB(
  value ~ 0 + trait + trait:temperature_between + trait:temperature_within +
    rr(0 + trait | individual, d = 1) + diag(0 + trait | individual) +
    rr(0 + trait | occasion, d = 1) + diag(0 + trait | occasion),
  family = gaussian(), data = my_long, dispformula = ~ 0,
  control = glmmTMBControl(optCtrl = list(iter.max = 1500, eval.max = 2000))
)

The corresponding gllvmTMB specification uses unique = TRUE, which represents the same shared-plus-diagonal target as the rr() plus diag() terms above. This is the route used below for an executable package-supported bootstrap.

library(gllvmTMB)

fit_gllvm <- gllvmTMB(
  value ~ 0 + trait + trait:temperature_between + trait:temperature_within +
    latent(0 + trait | individual, d = 1, unique = TRUE) +
    latent(0 + trait | occasion, d = 1, unique = TRUE),
  data = my_long, trait = "trait", unit = "individual", unit_obs = "occasion",
  family = gaussian(), REML = FALSE
)

Check the object you fitted

Check the model you fitted before reading its correlations. Run the block for your package. The interval example that follows uses gllvmTMB. If you are using glmmTMB, report the checked point estimate and use the interval guide to plan uncertainty for your fit.

Check your glmmTMB fit

summary(fit_glmm)
glmmTMB::diagnose(fit_glmm)

glmm_gradient <- max(abs(fit_glmm$sdr$gradient.fixed))
stopifnot(isTRUE(fit_glmm$fit$convergence == 0L), isTRUE(fit_glmm$sdr$pdHess),
          is.finite(glmm_gradient), glmm_gradient <= 0.01)

Check your gllvmTMB fit

gllvmTMB::check_gllvmTMB(fit_gllvm)
health <- fit_gllvm$fit_health
stopifnot(isTRUE(health$convergence == 0L), isTRUE(health$pd_hessian),
          isTRUE(is.finite(health$max_gradient) && health$max_gradient <= 0.01))

If your fit reports a boundary estimate, failed Hessian, large gradient, suspicious residual shape, or a response-scale problem, stop and diagnose it. Do not move straight to an interval. Diagnostics explains what each warning means and the next decision it should trigger.

Obtain an interval for your declared target

For an executable first bootstrap on your own data, use the fitted gllvmTMB object and retain the failure count and draws. The example requests covariance matrices, adjusted repeatability, and communality. In bootstrap_Sigma(), repeatability is named ICC; R instead denotes a correlation matrix. Calculate a B-minus-W contrast within each draw when that is your question; do not compare two marginal intervals.

set.seed(20260908)
own_boot <- gllvmTMB::bootstrap_Sigma(
  fit_gllvm,
  n_boot = 999,
  level = c("unit", "unit_obs"),
  what = c("Sigma", "ICC", "communality"),
  conf = 0.95,
  seed = 20260908,
  n_cores = 1,
  keep_draws = TRUE
)

own_boot$n_failed
own_boot$ci_lower
own_boot$ci_upper
saveRDS(own_boot, "own-data-bootstrap.rds")

For a direct B-minus-W contrast, extract the same trait pair from both matrices in every successful draw, then take percentiles of their difference. Replace the two trait names below with a pair from your declared suite.

correlation_from_draw <- function(draw, component, trait_1, trait_2) {
  x <- draw[[component]]
  if (is.null(x)) return(NA_real_)
  unname(stats::cov2cor(x)[trait_1, trait_2])
}

draws <- own_boot$draws
r_B <- vapply(draws, correlation_from_draw, numeric(1), component = "Sigma_B",
              trait_1 = "boldness", trait_2 = "activity")
r_W <- vapply(draws, correlation_from_draw, numeric(1), component = "Sigma_W",
              trait_1 = "boldness", trait_2 = "activity")
contrast <- r_B - r_W
if (sum(is.finite(contrast)) < 0.8 * length(contrast)) {
  stop("Too few usable bootstrap contrasts: inspect failures before reporting an interval.")
}
stats::quantile(contrast, c(0.025, 0.50, 0.975), na.rm = TRUE)

This is a model-conditional interval. It remains conditional on your retained rows, transformations, response family, mean model, rank, covariance convention, and refit outcomes. The empirical paper uses glmmTMB as its primary bootstrap, but its complete runner is deliberately campaign-specific because it records a frozen specification and every failure. For your own data, use the package-supported route above first, retain its full output, and see Uncertainty before comparing engines or making a B-minus-W claim. Treat 999 refits as a first practical run: before presenting a final interval, assess whether its endpoints are stable when you add retained refits and report the attempted, usable, and failed counts.

WarningDo not choose an effective sample size by copying an example

The faster extract_correlations(..., method = "wald") route needs a justified effective sample size. It is a sensitivity display, not a shortcut to a calibrated mixed-model confidence interval. Use the bootstrap first when interval evidence is needed.

What you can now report

You can now report your observation unit, covariance target, checked estimate and, if you ran the bootstrap, the interval and refit counts. Report and reproduce gives a reporting template. Before biological interpretation, revisit your response process, rank choice, residual diagnostics, and whether your chosen occasions support a within-individual question.