---
title: "From coefficients to expected outcomes"
subtitle: "Week 7: understanding coefficients, predictions and interactions"
order: 19
html-math-method: katex
format:
  aarhus-revealjs:
    embed-resources: true
    css: class-5-simulation.css
    transition: none
    incremental: false
    code-line-numbers: false
execute:
  echo: true
  warning: true
  message: false
  freeze: false
  eval: true
author:
  - name: Gavin Simpson
    affiliations: Aarhus University
date: "2026-10-21"
title-slide-attributes:
  data-background-color: "#003d73"
presenter:
  name: Gavin Simpson
  institute: Department of Animal & Veterinary Sciences
---

## After-class work

Allow 60–75 minutes: about 25 minutes using these slides, 25–35 minutes reading, and 10–15 minutes answering the [follow-up questions](after-class.html).

The two planned videos have not been recorded yet. These slides explain the examples while you work through the questions. You can use the recap and class results if you do not have the textbook.

Keep your script and answers for 28 October.

## Start with the same daily-gain data

Open the supplied Week 7 Posit Cloud project. The code below reads Group 1's data and fits the model from class. The outcome is average gain per pen, in g/day.

```{r}
#| label: after-gain-fit
source("glm-helpers.R")
d <- read_pen_data(1)
fit <- glm(response ~ diet + room,
           family = gaussian("identity"), data = d)
coef(summary(fit))[1:2, c("Estimate", "Std. Error")]
```

The intercept is expected gain for Control pens in Room 1. The diet row is the estimated High fibre minus Control difference.

## What is a reference category?

For a categorical variable, R chooses one category as the starting point for comparisons. This is the **reference category**.

Here, Control is the reference diet and Room 1 is the reference room. The intercept describes their combination.

Changing the reference diet changes what the intercept and diet coefficient describe. It should not change the predicted gain for the same diet and room.

## Change the starting point for the diet comparison

We copy `d` and use `relevel()` to make High fibre the reference in that copy. We then refit the same model.

```{r}
#| label: after-change-reference
d_relevelled <- d
d_relevelled$diet <- relevel(d$diet, ref = "High fibre")
fit_relevelled <- glm(response ~ diet + room,
  family = gaussian("identity"), data = d_relevelled)
c(Control_reference = unname(coef(fit)["(Intercept)"]),
  High_fibre_reference = unname(coef(fit_relevelled)["(Intercept)"]))
```

The two intercepts refer to different diets in Room 1, so their values differ.

## Check the predictions after changing the reference

`grid` lists both diets in Room 1. We predict gain using each fitted model and put the answers beside one another.

```{r}
#| label: after-response-predictions
grid <- subset(prediction_grid(d), room == "Room 1")
data.frame(grid,
  Control_reference = predict(fit, grid, type = "response"),
  High_fibre_reference = predict(fit_relevelled, grid,
                                 type = "response"))
```

For a given diet, do the two columns give the same predicted gain? Explain why that can happen even though the intercepts differ.

::: notes

The two fitted models describe the same expected gains. Only the way their coefficients express the comparison has changed. Do not imply that changing references creates a different biological effect.

:::


## Converting the linear predictor to an expected outcome

The linear predictor adds the intercept and the relevant diet and room contributions. The link tells us how to convert that sum into an expected outcome.

| Link used here | Conversion to the outcome we want to explain |
|---|---|
| Identity | No conversion: already expected gain in g/day |
| Log | Use `exp()` to obtain a positive expected count or feed conversion ratio |
| Logit | Use `plogis()` to obtain a probability between 0 and 1 |

In `predict()`, `type = "response"` asks R to make the conversion for you.

## Probability and odds describe the same chance differently

For Group 2, the event is **at least one pig in a pen needing treatment**.

If its probability is 0.30, about 30 out of 100 comparable pens would have the event. The odds are `0.30 / 0.70`: three pens with the event for every seven without it.

To turn odds back into probability, divide the odds by one plus the odds. We will use these two conversions in the next example.

## Compare two diets using an odds ratio

Use this illustrative example, rather than the fitted classroom numbers: the Control probability is 0.30 and the diet coefficient is −0.50 in a logit model.

Exponentiating the diet coefficient gives the High fibre / Control **odds ratio**. Multiply the Control odds by that ratio, then convert the new odds back to a probability.

Before running the calculation, do you expect the High fibre probability to be above or below 0.30? Explain using the negative coefficient.

## Work through the probability calculation

```{r}
#| label: odds-calculation
control_probability <- 0.30
control_odds <- control_probability / (1 - control_probability)
odds_ratio <- exp(-0.50)
high_odds <- control_odds * odds_ratio
high_probability <- high_odds / (1 + high_odds)
c(probability = high_probability, odds_ratio = odds_ratio,
  probability_change = high_probability - control_probability)
```

Read `probability` as the chance of the pen-level event under High fibre. `probability_change` subtracts the Control probability. The odds ratio and probability ratio are different comparisons.

::: notes

The High fibre probability is about.206 and the probability change is about−.094. An odds ratio of about.607 does not mean multiplying.30 by.607. These inputs illustrate the calculation; they are not estimates from the fitted classroom binary dataset.

:::


## Return to the study with diet and housing

We now use `data/factorial-pens.csv`, the separate study with 48 pens and four diet-and-housing combinations in every room.

We fit the interaction model because the question is whether the diet difference changes with housing. The reference categories are Control, Standard housing and Room 1.

```{r}
#| label: after-factorial-fit
f <- read_factorial_data()
interaction <- glm(gain ~ diet * housing + room,
                   family = gaussian("identity"), data = f)
coef(interaction)[
  c("dietHigh fibre", "dietHigh fibre:housingEnriched")]
```

## Predict the four average gains in Room 1

We list both diets under both housing conditions, keeping room unchanged. The table shows predicted average gains in g/day.

```{r}
#| label: after-factorial-predictions
grid <- expand.grid(diet = levels(f$diet),
  housing = levels(f$housing), room = "Room 1")
predictions <- predict_means(interaction, grid)
predictions[c("diet", "housing", "expected")]
```

Find the Control and High fibre rows for Standard housing. Then find the corresponding two rows for Enriched housing.

## Compare the diet differences between housing conditions

For each housing condition, subtract the Control prediction from the High fibre prediction. Then compare those two differences.

```{r}
#| label: after-interaction-contrast
diet_difference <- with(predictions,
  expected[diet == "High fibre"] - expected[diet == "Control"])
names(diet_difference) <- levels(f$housing)
diet_difference
c(difference_of_differences = unname(diff(diet_difference)))
```

Complete this sentence: "The estimated High fibre minus Control gain difference is ___ g/day larger in Enriched housing than in Standard housing."

::: notes

This is the interaction comparison in the Gaussian identity-link model. Students should state which two differences are compared, not merely repeat a technical label.

:::


## Be careful when comparing other kinds of outcomes

For gain with an identity link, an interaction asks whether a difference in expected gain changes with housing.

With a log link, it asks whether an expected-outcome ratio changes. With a logit link, it asks whether an odds ratio changes.

You do not need to fit these additional models today. For any model, first say what is measured and which comparison you want to explain.

## Prepare for observations from individual animals

Today, each row describes a pen. Next week, imagine recording a separate outcome for each of its six pigs. The pigs still share their pen's assigned diet, feed and environment.

Draw two pens with six pigs in each. Mark which diet is given to each pen.

Why might two pigs sharing a pen have more similar outcomes than pigs in different pens? Does recording more pigs change the number of pens independently assigned a diet?

::: notes

Ask students to name a shared condition such as feed, temperature or infection exposure. More animal observations may provide useful information, but they do not create more independently assigned pen diets. The individual-animal binary outcome next week is a different measurement from any pig treated in a pen.

:::


## Read with your class example beside you

In Touchon's second edition, use Chapter 7, *Generalized Linear Models*, to revisit a worked example similar to your group's outcome. Look for what is measured, the family and link, and how its fitted coefficients are explained.

Then use Chapter 6, *More Linear Models!*, to revisit interactions and predictions. Connect it to the diet-and-housing comparison we made in class.

If you cannot access the book, use the [recap](recap.html) and your group's output for the same practice.

## What to keep for next week

Save your script and write beside its model formula what your group measured, which explanatory variables were included, and which family and link were used.

Keep one written comparison of the diets in Room 1, including the interval showing uncertainty. Add your drawing of pigs grouped within pens and one question you would like to discuss on 28 October.
