Get startedGet started for free

Making predictions with interactions

1. Making predictions with interactions

Let's run through the prediction flow again, this time with the model containing an interaction. I'm hoping you get a sense of deja vu, because you've seen all this code before.

2. The model with the interaction

Here's the model of mass versus length and species with an interaction. I've used the version of the formula that gives the clearest coefficients, but I could also have used the simpler length times species syntax; it doesn't affect the predictions.

3. The prediction flow, again

Here's the code for the prediction flow. It's exactly the same as the code in the parallel slopes model. R will automatically take care of the interaction, so you don't need to change anything. I love it when things just work! The only thing to remember here is the use of expand_grid to get all the combinations of lengths and species.

4. Visualizing the predictions

Here's the plot of predictions - both ggplot's automatic prediction lines, and the points predicted from the model. The plot is identical to the one you saw in the first video of this chapter. This time however, the code is simpler because you don't have four separate models to worry about.

5. Manually calculating the predictions

To see how the predictions work, let's manually calculate them. First we get the coefficients from the model using the coefficients function. Then we use square bracket indexing to extract the four intercepts and the four slopes.

6. Manually calculating the predictions

As usual, we add the predictions as a column named after the response variable. We'll use case_when to distinguish the calculations for each species.

7. Manually calculating the predictions

The first species is bream, so the left-hand side of the first formula filters for rows containing bream.

8. Manually calculating the predictions

The calculation for the bream rows is the bream-specific intercept plus the bream-specific slope times the length of the fish.

9. Manually calculating the predictions

Then we repeat this for the other three species. The calculated values are the same as those returned by the predict function.

10. Let's practice!

Time for you to make some predictions.