# Use the repository's tutorial/ folder when running from the root.
# When rendering this page inside tutorial/, use the current folder instead.
tutorial_dir <- "tutorial"
if (!dir.exists(tutorial_dir)) tutorial_dir <- "."Do dogs that differ in one behaviour differ in others?
Following ten owner-reported behaviours across nine annual records
Our question. Dogs that are usually more fearful of other dogs may also be more sensitive to touch. But in years when one dog is more fearful than expected for that dog and year, is its touch-sensitivity score also higher? We can ask both questions because each dog was assessed repeatedly.
Choose a route. Start with one dog. To fit the model, follow the steps through Fit and check. Then read Figure 3 and recalculate the paper’s contrast. To read along without running R, jump from the records to the two correlations. Both routes end at Finish the example.
Follow one dog across three years
The Morris Animal Foundation supplied a teaching extract containing nine annual records for each of 100 dogs. Each row in the modified data represents one dog in one study year. Dog IDs have been replaced with randomized labels that preserve the link between a dog’s records. The data notes identify the data source, required acknowledgement and sharing conditions.
First, I locate the tutorial/ folder so the following steps can find the included data from either the repository root or inside tutorial/.
The data are in a comma-separated file, which base R can read with read.csv(). I print a few columns to see what each row contains.
dog_data_path <- file.path(tutorial_dir, "data", "dogs-modified.csv")
dogs <- read.csv(dog_data_path)
head(dogs[, c("study_year", "score_dog_directed_fear", "score_touch_sensitivity")]) study_year score_dog_directed_fear score_touch_sensitivity
1 0 0.00 0.75
2 1 1.75 0.25
3 2 2.00 0.50
4 3 2.50 0.50
5 4 2.00 0.25
6 5 1.75 0.50
Each row is one dog-year record. Owner-reported Canine Behavioral Assessment and Research Questionnaire (C-BARQ) composite scores range from 0 to 4. The ID in this file is a randomized label that links repeated records for the same dog. I use it to select one dog and put its records in year order. The ID is not printed.
example_dog_id <- dogs$dog_id[1]
one_dog <- subset(dogs, dog_id == example_dog_id)
one_dog <- one_dog[order(one_dog$study_year), ]
one_dog[1:3, c("study_year", "score_dog_directed_fear", "score_touch_sensitivity")] study_year score_dog_directed_fear score_touch_sensitivity
1 0 0.00 0.75
2 1 1.75 0.25
3 2 2.00 0.50
These are the first three years for this dog. Now I give the two scores shorter labels and put the same rows in a table.
three_years <- one_dog[1:3, c(
"study_year", "score_dog_directed_fear", "score_touch_sensitivity"
)]
names(three_years) <- c("Study year", "Dog-directed fear", "Touch sensitivity")
knitr::kable(
three_years,
row.names = FALSE,
caption = "Three annual records from one dog. Its randomized ID is used to select the records but is not shown."
)| Study year | Dog-directed fear | Touch sensitivity |
|---|---|---|
| 0 | 0.00 | 0.75 |
| 1 | 1.75 | 0.25 |
| 2 | 2.00 | 0.50 |
The scores vary across years for this dog. Three rows cannot establish a within-dog correlation. That estimate uses the repeated records from all dogs. Comparing dogs with one another answers a separate question.
Study year is coded 0 to 8, with 0 marking the first annual assessment. Before we look at the model results, I check why the example uses ten of the fourteen measured scores.
The extract has 14 scores. We keep the ten scores for which fewer than half of the 900 values are exactly zero. This was a post hoc choice for a manageable Gaussian teaching example. It reduces the most pronounced concentrations at zero; it does not establish that the retained scores are normally distributed. All 900 records and all 9,000 values for the ten chosen scores are retained.
# Find the score columns by their shared name prefix.
score_names <- grep("^score_", names(dogs), value = TRUE)
# Calculate the zero fraction separately for each behaviour.
zero_fraction <- colMeans(dogs[score_names] == 0)
round(zero_fraction, 3)score_stranger_directed_aggression score_owner_directed_aggression
0.476 0.911
score_dog_directed_aggression score_dog_directed_fear
0.457 0.354
score_dog_rivalry score_trainability
0.732 0.000
score_chasing score_stranger_directed_fear
0.028 0.803
score_nonsocial_fear score_separation_related_problems
0.231 0.563
score_touch_sensitivity score_excitability
0.497 0.016
score_attachment_attention_seeking score_energy
0.002 0.039
This output shows the fraction of dog-year records scored exactly zero for each behaviour. I remove the shared score_ prefix and replace underscores with spaces to make a labelled table that is easier to read.
behaviour_names <- sub("^score_", "", names(zero_fraction))
behaviour_names <- gsub("_", " ", behaviour_names)
zero_fraction_table <- data.frame(
Behaviour = behaviour_names,
Fraction_zero = round(zero_fraction, 3),
row.names = NULL
)
knitr::kable(
zero_fraction_table,
row.names = FALSE,
caption = "Fraction of records scored zero for each behaviour. The selection rule uses the unrounded fractions."
)| Behaviour | Fraction_zero |
|---|---|
| stranger directed aggression | 0.476 |
| owner directed aggression | 0.911 |
| dog directed aggression | 0.457 |
| dog directed fear | 0.354 |
| dog rivalry | 0.732 |
| trainability | 0.000 |
| chasing | 0.028 |
| stranger directed fear | 0.803 |
| nonsocial fear | 0.231 |
| separation related problems | 0.563 |
| touch sensitivity | 0.497 |
| excitability | 0.016 |
| attachment attention seeking | 0.002 |
| energy | 0.039 |
The selection rule retains scores with a zero fraction below 0.5.
retained_scores <- names(zero_fraction)[zero_fraction < 0.5]
retained_scores [1] "score_stranger_directed_aggression" "score_dog_directed_aggression"
[3] "score_dog_directed_fear" "score_trainability"
[5] "score_chasing" "score_nonsocial_fear"
[7] "score_touch_sensitivity" "score_excitability"
[9] "score_attachment_attention_seeking" "score_energy"
Fit and check the dog model
Extract the reproduction download. Run the terminal commands and the following R blocks from the folder containing tutorial/ and analysis/. Install digest, glmmTMB and gllvmTMB using Install the software. Install knitr if you want to recreate the displayed tables.
The preparation script selects and standardises ten scores and centres study year at the fifth record and divides it by about 2.58, the standard deviation of years 0–8. Look for 100 dogs, 900 dog-years and 9,000 scores.
Rscript --vanilla tutorial/data/prepare-dogs.RThe checked fitting script uses the same year adjustment and three axes at each level in both packages. It uses the gllvmTMB estimates to start the retained glmmTMB continuation, so this command needs both packages. On macOS or Linux, run both lines. In PowerShell, use $env:OPENBLAS_NUM_THREADS = "1"; $env:OMP_NUM_THREADS = "1" for the first line. Wait for the command to finish before opening its outputs. In the preview check, it took about two minutes.
export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1
Rscript --vanilla tutorial/downloads/dogs-main-ten/fit-dogs-main-ten.RIn R, select the mapped-start continuation and check it before reading its estimates. In the recorded run its maximum absolute gradient was 0.00317, below the 0.01 screen. If it fails, follow the dog fit guidance before interpreting the result.
dog_checks <- read.csv("analysis/cache/tutorial-data/dogs-main-ten-fit-checks.csv")
checked_dog <- subset(dog_checks, engine == "glmmTMB" & fit == "gllvmTMB-mapped start")
checked_dog
if (nrow(checked_dog) != 1L || !isTRUE(checked_dog$passes_teaching_screen)) {
stop("The dog fit did not pass. Check the diagnostics before reporting a result.")
}Print the fear–touch sensitivity correlations from this fit.
dog_points <- read.csv("analysis/cache/tutorial-data/dogs-main-ten-point-results.csv")
fresh_dog <- subset(dog_points, engine == "glmmTMB")
stopifnot(nrow(fresh_dog) == 2L, all(fresh_dog$fit_passes_teaching_screen))
fresh_dog[, c("level", "fear_touch_correlation")]What are the two correlations asking?
The between-dog correlation asks whether dogs rated as more fearful than other dogs tend also to have higher touch-sensitivity scores. The within-dog correlation asks whether a dog’s touch-sensitivity score is higher in years when its fear score is higher than expected after accounting for the dog’s usual level and the average study-year trend. We allow each score to change linearly with study year before estimating these associations. This term describes the average trend across dogs. Nonlinear changes or trajectories that differ among dogs can still contribute to the fitted within-dog association.
Predict. If the between-dog correlation is 0.50 and the within-dog correlation is 0.17, what is the between-minus-within difference? Calculate it before opening the answer.
Check your prediction
between_minus_within <- 0.50 - 0.17
between_minus_within[1] 0.33
The rounded values give a difference of 0.33. The exact archived estimates later in this lesson give a difference of 0.327. The example pair was chosen after inspecting the results to illustrate the comparison.
Correlations: between dogs and within dogs
In each matrix, the upper triangle gives a correlation estimate. The lower triangle gives the lower and upper limits of its 95% bootstrap interval. A star marks an interval that excludes zero. Read the same pair in both matrices to compare between-dog and within-dog associations.
At narrow widths, Tab to the correlation matrices and use the arrow keys to scroll. The exact-value table below gives the estimates and limits.
The full plotting code is shown beside this figure in the Figure Gallery, where you can copy it or download the R script. It draws the matrix from the archived aggregate estimates and interval limits; it does not refit the models or rerun the bootstrap. The Figure Gallery README lists its R package requirements and where it saves the plot.
The matrix is a compact view of 45 behaviour pairs at two levels. The table below gives the same values in text, so you can compare each pair without relying on the colours or small labels in the figure. Each estimate is followed by its pointwise 95% parametric-bootstrap interval.
Show how the table is made from the included results
dog_correlation_path <- file.path(
tutorial_dir, "downloads", "figure-gallery", "data", "dogs-correlations.csv"
)
dog_correlations <- read.csv(dog_correlation_path)
between_dogs <- subset(dog_correlations, level == "Between dogs")
within_dogs <- subset(dog_correlations, level == "Within dogs")
dog_correlation_table <- merge(
between_dogs[, c("trait1", "trait2", "estimate", "lower_95", "upper_95")],
within_dogs[, c("trait1", "trait2", "estimate", "lower_95", "upper_95")],
by = c("trait1", "trait2"),
suffixes = c("_between", "_within"),
sort = FALSE
)
dog_correlation_table$`Between dogs` <- with(
dog_correlation_table,
sprintf("%.3f [%.3f, %.3f]", estimate_between, lower_95_between, upper_95_between)
)
dog_correlation_table$`Within dogs` <- with(
dog_correlation_table,
sprintf("%.3f [%.3f, %.3f]", estimate_within, lower_95_within, upper_95_within)
)
dog_correlation_table$`Behaviour pair` <- paste(
dog_correlation_table$trait1,
dog_correlation_table$trait2,
sep = " and "
)
dog_correlation_table <- dog_correlation_table[, c(
"Behaviour pair", "Between dogs", "Within dogs"
)]
names(dog_correlation_table) <- c(
"Behaviour pair",
"Between-dog correlation [95% interval]",
"Within-dog correlation [95% interval]"
)
knitr::kable(
dog_correlation_table,
format = "html",
row.names = FALSE,
table.attr = 'class="mobile-results-table"',
caption = "All 45 dog behaviour pairs. Entries show the correlation estimate and its pointwise 95% parametric-bootstrap interval."
)| Behaviour pair | Between-dog correlation [95% interval] | Within-dog correlation [95% interval] |
|---|---|---|
| Stranger-directed aggression and Dog-directed aggression | 0.338 [0.184, 0.490] | 0.304 [0.240, 0.366] |
| Stranger-directed aggression and Dog-directed fear | 0.206 [-0.007, 0.418] | 0.131 [0.083, 0.196] |
| Stranger-directed aggression and Trainability | 0.023 [-0.199, 0.237] | -0.065 [-0.112, -0.027] |
| Stranger-directed aggression and Chasing | 0.340 [0.170, 0.498] | 0.127 [0.082, 0.182] |
| Stranger-directed aggression and Nonsocial fear | 0.110 [-0.060, 0.285] | 0.094 [0.023, 0.160] |
| Stranger-directed aggression and Touch sensitivity | 0.288 [0.108, 0.464] | 0.090 [0.035, 0.141] |
| Stranger-directed aggression and Excitability | 0.405 [0.250, 0.563] | 0.158 [0.101, 0.220] |
| Stranger-directed aggression and Attachment and attention seeking | 0.304 [0.146, 0.454] | 0.102 [0.056, 0.154] |
| Stranger-directed aggression and Energy | 0.393 [0.220, 0.555] | 0.078 [0.025, 0.133] |
| Dog-directed aggression and Dog-directed fear | 0.419 [0.229, 0.579] | 0.304 [0.242, 0.365] |
| Dog-directed aggression and Trainability | 0.219 [-0.009, 0.441] | -0.118 [-0.182, -0.051] |
| Dog-directed aggression and Chasing | 0.243 [0.065, 0.403] | 0.155 [0.083, 0.222] |
| Dog-directed aggression and Nonsocial fear | 0.093 [-0.071, 0.267] | 0.133 [0.066, 0.208] |
| Dog-directed aggression and Touch sensitivity | 0.268 [0.090, 0.435] | 0.101 [0.031, 0.168] |
| Dog-directed aggression and Excitability | 0.350 [0.172, 0.498] | 0.108 [0.040, 0.174] |
| Dog-directed aggression and Attachment and attention seeking | 0.301 [0.147, 0.444] | 0.063 [-0.006, 0.131] |
| Dog-directed aggression and Energy | 0.365 [0.182, 0.532] | -0.010 [-0.079, 0.056] |
| Dog-directed fear and Trainability | 0.063 [-0.186, 0.292] | -0.088 [-0.136, -0.049] |
| Dog-directed fear and Chasing | -0.018 [-0.220, 0.194] | 0.101 [0.052, 0.151] |
| Dog-directed fear and Nonsocial fear | 0.335 [0.131, 0.506] | 0.266 [0.199, 0.330] |
| Dog-directed fear and Touch sensitivity | 0.501 [0.327, 0.642] | 0.174 [0.114, 0.239] |
| Dog-directed fear and Excitability | 0.289 [0.076, 0.474] | 0.098 [0.037, 0.155] |
| Dog-directed fear and Attachment and attention seeking | 0.201 [-0.027, 0.414] | 0.070 [0.022, 0.115] |
| Dog-directed fear and Energy | -0.038 [-0.250, 0.174] | -0.027 [-0.086, 0.022] |
| Trainability and Chasing | 0.042 [-0.172, 0.247] | -0.055 [-0.091, -0.019] |
| Trainability and Nonsocial fear | -0.227 [-0.422, 0.015] | -0.109 [-0.174, -0.047] |
| Trainability and Touch sensitivity | -0.197 [-0.404, 0.043] | -0.077 [-0.125, -0.035] |
| Trainability and Excitability | -0.015 [-0.246, 0.223] | -0.064 [-0.117, -0.011] |
| Trainability and Attachment and attention seeking | 0.127 [-0.097, 0.331] | -0.045 [-0.082, -0.009] |
| Trainability and Energy | 0.337 [0.114, 0.523] | -0.009 [-0.052, 0.037] |
| Chasing and Nonsocial fear | 0.019 [-0.144, 0.184] | 0.114 [0.048, 0.176] |
| Chasing and Touch sensitivity | 0.154 [-0.038, 0.332] | 0.101 [0.054, 0.150] |
| Chasing and Excitability | 0.322 [0.150, 0.476] | 0.159 [0.097, 0.218] |
| Chasing and Attachment and attention seeking | 0.253 [0.096, 0.400] | 0.106 [0.062, 0.152] |
| Chasing and Energy | 0.402 [0.232, 0.564] | 0.081 [0.027, 0.139] |
| Nonsocial fear and Touch sensitivity | 0.286 [0.128, 0.453] | 0.290 [0.225, 0.356] |
| Nonsocial fear and Excitability | 0.154 [-0.024, 0.311] | 0.132 [0.070, 0.201] |
| Nonsocial fear and Attachment and attention seeking | 0.053 [-0.095, 0.203] | 0.104 [0.043, 0.168] |
| Nonsocial fear and Energy | -0.102 [-0.288, 0.087] | -0.050 [-0.117, 0.022] |
| Touch sensitivity and Excitability | 0.339 [0.172, 0.507] | 0.130 [0.072, 0.189] |
| Touch sensitivity and Attachment and attention seeking | 0.194 [0.011, 0.379] | 0.096 [0.048, 0.148] |
| Touch sensitivity and Energy | 0.059 [-0.156, 0.254] | 0.004 [-0.054, 0.058] |
| Excitability and Attachment and attention seeking | 0.302 [0.144, 0.457] | 0.162 [0.104, 0.218] |
| Excitability and Energy | 0.351 [0.160, 0.521] | 0.146 [0.080, 0.210] |
| Attachment and attention seeking and Energy | 0.343 [0.147, 0.505] | 0.093 [0.042, 0.146] |
The values come from the included aggregate results used to draw Figure 3; this table does not refit the models or rerun the bootstrap. You can also download the correlation data as CSV.
The Figure 3 redraw instructions use the same saved tables.
For dog-directed fear and touch sensitivity, the estimated correlation was 0.501 between dogs (95% interval 0.327 to 0.642) and 0.174 within dogs (0.114 to 0.239). Dogs usually rated as more fearful also tended to receive higher touch-sensitivity scores. Across years, deviations in the two scores were positively associated, but the estimated association was weaker.
In Figure 3, find the row and column labelled Dog-directed fear and Touch sensitivity. The upper triangle shows each point estimate; the lower triangle shows its lower and upper interval limits. Read the same trait pair in both matrices to compare the levels.
We compare the levels by calculating the difference in each paired bootstrap refit. Both packages refitted each simulated dataset and helped determine which datasets qualified. For each retained dataset, subtract the within-dog correlation from the between-dog correlation from its selected glmmTMB refit. Then take percentiles of those differences. For fear and touch sensitivity, the observed between-minus-within difference was 0.327, with a 95% interval from 0.139 to 0.491. Because this interval is above zero, the fitted association was stronger between dogs than within dogs in this example. The downloadable contrast table lists all 45 pairwise differences and their percentile limits. The table gives the saved result.
Show how the interval table is made
contrast_path <- "tutorial/downloads/dogs-main-ten/dogs-correlation-contrasts.csv"
if (!file.exists(contrast_path)) {
contrast_path <- "downloads/dogs-main-ten/dogs-correlation-contrasts.csv"
}
dog_contrasts <- read.csv(contrast_path)
selected_contrast <- subset(
dog_contrasts,
trait1 == "Dog-directed fear" & trait2 == "Touch sensitivity"
)
contrast_display <- data.frame(
quantity = "Between minus within",
result = sprintf(
"%.3f (%.3f to %.3f); %s paired refits",
selected_contrast$estimate,
selected_contrast$lower_95,
selected_contrast$upper_95,
selected_contrast$retained_paired_refits
)
)
names(contrast_display) <- c(
"Quantity", "Estimate (95% interval) and paired refits"
)
knitr::kable(
contrast_display,
format = "html",
row.names = FALSE,
table.attr = 'class="mobile-results-table"',
caption = "Direct parametric-bootstrap contrast for dog-directed fear and touch sensitivity."
)| Quantity | Estimate (95% interval) and paired refits |
|---|---|
| Between minus within | 0.327 (0.139 to 0.491); 1095 paired refits |
Separate intervals for the two correlations do not directly answer this comparison. The model describes the scores and does not establish why they are associated; owner reporting may contribute to their covariance.
The repository also includes the derived target values from the 1,095 retained paired refits. Draw numbers are shuffled and reassigned, and the file contains no individual dog records or fitted objects. I first keep the saved draws for fear and touch sensitivity and check how many paired refits they contain. Then I calculate the 95% interval from those values:
dog_draw_path <- "tutorial/downloads/bootstrap/main-examples/dogs-target-draws.csv.gz"
if (!file.exists(dog_draw_path)) {
dog_draw_path <- "downloads/bootstrap/main-examples/dogs-target-draws.csv.gz"
}
dog_target_draws <- read.csv(gzfile(dog_draw_path))
# Keep draws for between-dog minus within-dog correlation in these behaviours.
fear_touch_draws <- subset(
dog_target_draws,
quantity == "correlation_contrast" &
level == "between_minus_within" &
trait_1 == "Dog-directed fear" & trait_2 == "Touch sensitivity"
)
nrow(fear_touch_draws)[1] 1095
You should see 1,095 draws. Now take the lower and upper percentiles.
round(quantile(fear_touch_draws$value, c(0.025, 0.975)), 3) 2.5% 97.5%
0.139 0.491
The bootstrap draw guide describes these files and their limits. The included base-R script calculates intervals for every listed target.
The intervals are pointwise percentiles from a parametric bootstrap. Of 1,200 simulated datasets, 1,095 met the recorded paired eligibility rules. For each retained dataset, both level estimates came from the same selected glmmTMB refit. The intervals are conditional on the fitted model and those rules. We have not tested how often this procedure captures the true values in repeated studies, so the intervals should not be read as a verified 95% success rate. The repository provides anonymised, derived target draws so readers can recalculate the displayed percentiles. It does not include original replicate IDs, fitted objects, individual simulated responses, or the campaign runner needed to rerun or audit the full bootstrap campaign.
How were the dog bootstrap refits selected?
For each package, an initial fit with positive between-dog unique variances had to pass the eligibility checks. We then selected the highest-likelihood eligible fit from the two starts. In 1,111 datasets, each package had an eligible fit from this positive-between start. Sixteen were then excluded because an ineligible candidate had a log likelihood more than 0.001 higher than the selected candidate in at least one package. The remaining 1,095 paired datasets were retained. A positive Hessian in both packages was not required; 721 retained pairs met that additional condition. The level estimates in each retained dataset came from the same selected glmmTMB refit.
Finish the example
Report the paper’s result. After accounting for study year, dogs usually rated as more fearful of other dogs also tended to be more touch-sensitive. The fitted association was stronger among dogs than across years within the same dog (between minus within 0.327, 95% bootstrap interval 0.139 to 0.491).
Report your fresh fit. Give the two correlations printed by your checked fit. The interval above comes from the paper’s saved fit and its 1,095 retained paired refits.
You’ve finished the main lesson when you can explain what was compared across dogs and within dogs, how year entered the model, and what the contrast interval says. Use your data starts with your own individual, occasion and trait columns.
Go further
Read Figure 4 for shared axes, communality and repeatability. See study-year estimates, the rank comparison, or the figure redraw scripts. The fit-check guide and bootstrap records explain the checks in more detail.
Ordination: how do all ten behaviours vary together?
The correlation matrices answer pairwise questions. The ordination gives a view of the joint pattern across all ten scores. The model uses three shared axes at each level. An axis is a summary direction for behaviours that vary together. Each arrow shows a behaviour’s loading, which tells how strongly and in which direction it contributes to an axis. We use varimax, an orthogonal rotation, to turn the axes for easier interpretation. It changes the display, not the covariance represented by the model. We rotate the between- and within-dog axes separately, and rotate the dog positions with them. Thus, axis 1 between dogs need not describe the same combination of behaviours as axis 1 within dogs. In panel A, a conditional score is a dog’s fitted position on the shared axes given its records. Panel B shows the fitted positions of individual dog-years.
The numbers beside the loading arrows refer to the dog trait key. Use it to match each numbered arrow to its behaviour. The plotted points are estimated dog or dog-year scores, not individual behaviours.
If the panels look small on a narrow screen or at 200% zoom, press Tab until the figure has a visible outline, then use the arrow keys to scroll horizontally. The tables below give the exact values.
The full code for the six ordination projections, communality and repeatability is shown beside Figure 4 in the Figure Gallery, and is available as a downloadable R script. It uses the bundled, ID-free score coordinates, loadings and summary tables. The script redraws the figure but does not refit the model or rerun the bootstrap. The Figure Gallery README lists its R package requirements and output paths.
The communality table and repeatability table provide the plotted estimates and limits for each behaviour. The rotated dog scores and loadings provide the values shown in the six ordination panels. On a small screen, open the full-size figure or use these tables to inspect the plotted values.
In panel C, circles and triangles are point estimates, and capped horizontal lines show 95% parametric-bootstrap percentile limits. The scale leaves a small margin beyond 1 so limits at the upper bound do not end on the plot frame. Use the communality table to read exact endpoints when a short line is partly covered by its marker.
To redraw this figure from those bundled inputs, run this command from the repository root:
Rscript --vanilla tutorial/downloads/figure-gallery/make-figure-4.RThe fear–touch matrix correlation combines their shared covariance across all three axes and scales it by each behaviour’s full variation, including the part not represented by the shared axes. In the between-dog projection of axes 1 and 3, follow the heavier solid arrow for dog-directed fear (3) and the heavier dashed arrow for touch sensitivity (7). Both point in a similar direction along axis 3, suggesting a positive association. The loading table gives their exact coordinates. The two-axis picture helps us see the broader pattern, but it cannot give the full matrix correlation. The Figure Gallery also supplies the separately rotated scores and loadings, and the full trait key.
Repeatability: how much variation lies between dogs?
Repeatability divides the between-dog variance by the sum of the between- and within-dog variances. For energy it was 0.567 (95% interval 0.485 to 0.636). In other words, just over half of the modelled variation in energy was associated with differences between dogs after accounting for the year trend. Communality uses the variance at one level as its denominator, so the two quantities answer different questions.
The repeatability table gives estimates and intervals for all ten behaviours. Chasing had the highest point estimate, 0.728, and trainability the lowest, 0.317.
Optional: fit the models step by step and inspect the checks
The following route is for readers who want to see the model calls in R. Use it instead of the one-command fit in Fit and check. It creates fitted objects in the current R session, including fit_glmm_mapped, which is used by the year-effects calculation below. The commands are set not to run when the page is rendered. In the recorded run on the bundled randomized-ID data, the independent glmmTMB and gllvmTMB fits took about 17 and 101 seconds, respectively; times depend on the computer and software. These calls produce fresh fits, so their numerical results need not equal the archived values shown above.
The packages write the same covariance model in different ways. In glmmTMB, rr() describes the shared axes, while diag() and trait-specific Gaussian dispersion supply unique variance. In gllvmTMB, unique = TRUE includes the corresponding trait-specific variances. Its Gaussian fit also has a small fixed observation variance (about \(10^{-6}\)); include this once in the within-dog variance, without adding another residual term.
library(glmmTMB)
library(gllvmTMB)
prepared <- readRDS("analysis/cache/tutorial-data/dogs-ten-year-adjusted.rds")
d <- prepared$long
set.seed(20261130)
fit_glmm <- glmmTMB(
value ~ 0 + trait + trait:year_c +
rr(0 + trait | individual, d = 3) + diag(0 + trait | individual) +
rr(0 + trait | occasion, d = 3),
data = d, family = gaussian(), dispformula = ~ 0 + trait, REML = FALSE,
control = glmmTMBControl(optCtrl = list(iter.max = 1500, eval.max = 2000))
)
set.seed(20261130)
fit_gllvm <- gllvmTMB(
value ~ 0 + trait + trait:year_c +
latent(0 + trait | individual, d = 3, unique = TRUE) +
latent(0 + trait | occasion, d = 3, unique = TRUE),
data = d, trait = "trait", unit = "individual", unit_obs = "occasion",
family = gaussian(), REML = FALSE,
control = gllvmTMBcontrol(
optimizer = "nlminb", n_init = 1, init_jitter = 0,
start_method = list(method = "indep"),
optArgs = list(control = list(iter.max = 1500, eval.max = 2000))
)
)Check convergence, gradients, the Hessian and reconstructed covariance matrices before treating fresh fits as matching. The optimiser tries to minimise a quantity, here the negative log-likelihood. The gradient measures how sensitive that quantity is to very small changes in the fitted parameters. A smaller maximum absolute gradient means the quantity changes less under those small adjustments. The Hessian describes its curvature around that point; a positive-definite Hessian is consistent with a local minimum of the negative log-likelihood. Neither check proves that the fit is the best solution. For these point fits, the recorded screen required convergence code zero, finite likelihood and estimates, maximum absolute gradient no greater than 0.01, a positive-definite Hessian, and a valid covariance reconstruction. The 0.01 threshold is a numerical screen for this analysis, not a biological cutoff. It is separate from the paired-bootstrap retention rule above.
In the recorded run (glmmTMB 1.1.14 and gllvmTMB 0.7.1), the independent glmmTMB start had AIC 18,960.066 and a positive Hessian, but its maximum absolute gradient was 0.0373. It therefore did not pass the 0.01 gradient screen. The independent gllvmTMB start had AIC 18,958.934 and gradient 0.00306, so it passed that screen. The independent fits also gave different between-dog covariance matrices: their largest absolute difference was 0.108, compared with 0.00089 within dogs. These are differences between entries of covariance matrices on the standardised-score variance scale, not differences between correlations. Both fits placed at least one between-dog unique variance near zero, where the likelihood can be difficult to optimise. This boundary is a plausible contributor to the discrepancy, but it does not by itself explain it.
Starting glmmTMB from the gllvmTMB estimates and then using BFGS, a second optimisation algorithm, gave a glmmTMB fit that passed the numerical screen (maximum absolute gradient 0.00317, positive Hessian) and had AIC 18,958.934. Its reconstructed between- and within-dog covariance matrices differed from the gllvmTMB matrices by at most 1.4e-6 after including the small Gaussian observation variance once. Thus, the packages gave nearly identical covariance estimates for this mapped-start comparison, while independent starts led to different solutions. This is evidence about these fits, not a guarantee that the optimisers will agree for every dataset or start. The code blocks below first check the independent fits and then reproduce the mapped-start comparison using gllvmTMB 0.7.1 object parameters; those parameter names are package-version-specific. The gallery figures use the separately archived fit and bootstrap; do not combine a new fit with those archived intervals unless you establish that they refer to the same fitted model.
The code below uses the same extraction and diagnostic helpers as the standalone fit script. The helper adds the small Gaussian observation variance once. The covariance gaps compare the largest entry-wise differences in the reconstructed matrices.
source("tutorial/downloads/dogs-main-ten/fit-helpers.R")
traits <- prepared$traits
mats_glmm <- extract_glmm(fit_glmm, traits)
mats_gllvm <- extract_gllvm(fit_gllvm, traits)
rbind(screen_fit(fit_glmm, "glmmTMB", "independent start", mats_glmm),
screen_fit(fit_gllvm, "gllvmTMB", "independent start", mats_gllvm))
c(between_covariance_gap = max(abs(mats_glmm$B_total - mats_gllvm$B_total)),
within_covariance_gap = max(abs(mats_glmm$W_total - mats_gllvm$W_total)))Gradient and AIC may vary with package version and starting values. For fits to identical data and models, use the lowest AIC among fits that pass the screen. To see whether the fits can be brought into closer agreement, we can initialise a second glmmTMB fit with the fixed effects and covariance parameters from gllvmTMB, then optimise those parameters with BFGS. This is a sensitivity check, not an independent comparison of the two optimisers.
p <- fit_gllvm$opt$par
epsilon <- as.numeric(fit_gllvm$report$sigma_eps)
start_from_gllvm <- list(
beta = unname(p[names(p) == "b_fix"]),
theta = unname(c(p[names(p) == "theta_rr_B"],
p[names(p) == "theta_diag_B"],
p[names(p) == "theta_rr_W"])),
betadisp = unname(log(sqrt(exp(2 * p[names(p) == "theta_diag_W"]) + epsilon^2)))
)
fit_glmm_mapped <- glmmTMB(
value ~ 0 + trait + trait:year_c +
rr(0 + trait | individual, d = 3) + diag(0 + trait | individual) +
rr(0 + trait | occasion, d = 3),
data = d, family = gaussian(), dispformula = ~ 0 + trait, REML = FALSE,
start = start_from_gllvm,
control = glmmTMBControl(
optimizer = optim, optArgs = list(method = "BFGS"),
optCtrl = list(maxit = 3000, reltol = 1e-12)
)
)
mats_glmm_mapped <- extract_glmm(fit_glmm_mapped, traits)
screen_fit(fit_glmm_mapped, "glmmTMB", "mapped start", mats_glmm_mapped)
c(between_covariance_gap = max(abs(mats_glmm_mapped$B_total - mats_gllvm$B_total)),
within_covariance_gap = max(abs(mats_glmm_mapped$W_total - mats_gllvm$W_total)))The diagnostics lesson explains the checks and covariance reconstruction for the archived examples. The Figure Gallery README lists the plotting packages, input tables and output paths.
For a qualified gllvmTMB fit, the package can extract scores and loadings and make a varimax-rotated ordination directly. The commands draw the fitted ordination at each level. With three axes, some builds display all three pairwise projections together. Check the facet labels to see which axes your plot displays. The extractor returns the fitted coordinates; the plot method applies varimax. The archived figure uses separately varimax-rotated glmmTMB scores and loadings, so a fresh native plot need not have the same orientation or coordinates.
ordination_B <- gllvmTMB::extract_ordination(fit_gllvm, level = "unit")
ordination_W <- gllvmTMB::extract_ordination(fit_gllvm, level = "unit_obs")
head(ordination_B$scores)
ordination_B$loadings
plot(fit_gllvm, type = "ordination", level = "unit", axes = c(1, 2),
rotation = "varimax", sign_anchor = "auto")
plot(fit_gllvm, type = "ordination", level = "unit_obs", axes = c(1, 2),
rotation = "varimax", sign_anchor = "auto")What changed over study years?
The table gives the estimated average change in each standardised score per study year. The 95% intervals are normal-based Wald intervals calculated from the coefficient and its standard error, rather than bootstrap intervals. Trainability increased on average by about 0.149 standard deviations per study year; energy decreased by about 0.129. These averages do not mean that every dog changed at the same rate.
| Behaviour | Change per year | SE | Lower 95% | Upper 95% |
|---|---|---|---|---|
| Stranger-directed aggression | 0.000 | 0.008 | -0.015 | 0.015 |
| Dog-directed aggression | 0.047 | 0.008 | 0.032 | 0.062 |
| Dog-directed fear | -0.020 | 0.009 | -0.036 | -0.003 |
| Trainability | 0.149 | 0.010 | 0.130 | 0.169 |
| Chasing | -0.026 | 0.007 | -0.039 | -0.013 |
| Nonsocial fear | 0.015 | 0.007 | 0.001 | 0.030 |
| Touch sensitivity | 0.002 | 0.008 | -0.013 | 0.018 |
| Excitability | -0.037 | 0.008 | -0.054 | -0.021 |
| Attachment and attention seeking | -0.024 | 0.008 | -0.040 | -0.009 |
| Energy | -0.129 | 0.008 | -0.144 | -0.113 |
Optional: recreate the year-effect table from a fresh fit
The table uses the glmmTMB fit that passed the numerical screen after starting from the gllvmTMB estimates. To recreate it, first run the optional fitting section above through the mapped-start check. The model used a scaled version of study year, where \(x=(\text{year}-4)/\sqrt{(60/9)}\). First, extract each score’s year coefficient and standard error from that fit:
beta <- glmmTMB::fixef(fit_glmm_mapped)$cond
V <- as.matrix(vcov(fit_glmm_mapped)$cond)
year_terms <- grep(":year_c$", names(beta), value = TRUE)
year_coefficients <- data.frame(
term = year_terms,
coefficient = unname(beta[year_terms]),
se = sqrt(diag(V)[year_terms])
)
year_coefficientsThese coefficients describe change for a one-unit increase in the scaled year. To express change per study year, divide each estimate and standard error by \(\sqrt{(60/9)}\). The interval is the estimate plus or minus 1.96 standard errors:
year_scale <- sqrt(60 / 9)
# Cutoff for a two-sided 95% normal interval (about 1.96).
critical_value <- qnorm(0.975)
year_effects <- data.frame(
term = sub(":year_c$", "", year_coefficients$term),
change_per_year = year_coefficients$coefficient / year_scale,
se = year_coefficients$se / year_scale
)
year_effects$lower_95 <- year_effects$change_per_year - critical_value * year_effects$se
year_effects$upper_95 <- year_effects$change_per_year + critical_value * year_effects$se
year_effectsThis is a normal-based Wald interval. It differs from the parametric-bootstrap intervals used for the correlations and communalities.

