1. Two-way ANOVA: cow weight gain

1.1 Preparation

# Import the data
growth.moo <- read.csv("/Users/aaronsi/Documents/Documents - Aaron’s MacBook Pro/4259A/data/growth.csv")

# Load tools for data summaries, plots, and model diagnostic plots.
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(ggfortify)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
# Apply the same simple style to all plots.
theme_set(theme_bw(base_size = 12) +
  theme(panel.grid.minor = element_blank(), legend.position = "bottom"))

1.2 Check the number of observations, column names, and variable types.

glimpse(growth.moo)
## Rows: 48
## Columns: 3
## $ supplement <chr> "supergain", "supergain", "supergain", "supergain", "contro…
## $ diet       <chr> "wheat", "wheat", "wheat", "wheat", "wheat", "wheat", "whea…
## $ gain       <dbl> 17.37125, 16.81489, 18.08184, 15.78175, 17.70656, 18.22717,…

1.3 Check and arrange the data

# Convert diet and supplement to categorical variables for the ANOVA.
growth.moo <- mutate(growth.moo,
                     diet = factor(diet),
                     supplement = factor(supplement))

# Display their levels to check the treatment names and order.
levels(growth.moo$diet)
## [1] "barley" "oats"   "wheat"
levels(growth.moo$supplement)
## [1] "agrimore"  "control"   "supergain" "supersupp"

1.4 Reference level

# Compare supplements with the control treatment.
growth.moo <- 
  mutate(growth.moo,
         supplement = relevel(supplement, ref = "control"))

levels(growth.moo$supplement)
## [1] "control"   "agrimore"  "supergain" "supersupp"

1.5 Data exploration

# Check missing values, the response range, and treatment replication.
colSums(is.na(growth.moo))
## supplement       diet       gain 
##          0          0          0
summary(growth.moo$gain)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   15.78   19.28   21.25   21.39   23.63   29.03
with(growth.moo, table(diet, supplement))
##         supplement
## diet     control agrimore supergain supersupp
##   barley       4        4         4         4
##   oats         4        4         4         4
##   wheat        4        4         4         4
# Compare individual gains and their spread within each treatment.
ggplot(growth.moo, aes(x = supplement, y = gain, colour = diet)) +
  geom_boxplot(
    outlier.shape = NA,
    width = 0.45,
    fill = "grey95",
    linewidth = 0.5
  ) +
  geom_point(
    position = position_jitter(width = 0.05, height = 0, seed = 4259),
    size = 2,
    alpha = 0.8
  ) +
  facet_wrap(~ diet, ncol = 1) +
  scale_colour_brewer(palette = "Dark2") +
  labs(x = "Supplement", y = "Weight gain") +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank(),
    strip.text = element_text(face = "bold"),
    legend.position = "none"
  )

  • There are no missing values, each treatment combination has four cows.
  • Both predictors are categorical and fully crossed, so that a correlation matrix is not needed.
  • The plot checks unusual observations within treatments; all observations are retained. Independence is assumed between cows.
  • Normality and equal variance are assessed using residuals after fitting.

1.6 Means and interaction plots

# Group cows by both diet and supplement, then calculate each cell mean.

sumMoo <- growth.moo %>%
  group_by(diet, supplement) %>%
  summarise(meanGrow = mean(gain))
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by diet and supplement.
## ℹ Output is grouped by diet.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(diet, supplement))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
sumMoo
## # A tibble: 12 × 3
## # Groups:   diet [3]
##    diet   supplement meanGrow
##    <fct>  <fct>         <dbl>
##  1 barley control        23.3
##  2 barley agrimore       26.3
##  3 barley supergain      22.5
##  4 barley supersupp      25.6
##  5 oats   control        20.5
##  6 oats   agrimore       23.3
##  7 oats   supergain      19.7
##  8 oats   supersupp      21.9
##  9 wheat  control        17.4
## 10 wheat  agrimore       19.6
## 11 wheat  supergain      17.0
## 12 wheat  supersupp      19.7
  • The resulting table has one row for each of the 12 treatment combinations.
# Plot the treatment means against supplement, as in the first chapter plot.
ggplot(sumMoo, aes(x = supplement, y = meanGrow)) + 
  geom_point(size = 2.5) +
  labs(x = "Supplement", y = "Mean weight gain") +
  theme_get()

  • Diet is not distinguished yet; the next plot adds that information.
# Use colour to identify diets and group to connect means within each diet.
ggplot(sumMoo, aes(x = supplement, y = meanGrow,
                   colour = diet, group = diet)) +
  geom_point(size = 2.5) +
  geom_line() +
  scale_colour_brewer(palette = "Dark2") +
  labs(x = "Supplement", y = "Mean weight gain", colour = "Diet") +
  theme_get()

  • The profiles are approximately parallel which means supplement effects appear to be similar across diets.
  • Barley generally has the highest mean gains and wheat has the lowest.

1.7 Fit the model and check assumptions

  • The null hypothesis for the interaction is that the effect of supplement on weight gain does not depend on diet.
# Fits diet, supplement, and their interaction.
model_cow <- lm(gain ~ diet * supplement, data = growth.moo)
              

# Check residual shape, spread, normality, and leverage.
autoplot(model_cow, smooth.colour = NA) +
  theme(axis.text.x = element_text(size = 7, angle = 60, hjust = 1))
## Warning: `fortify(<lm>)` was deprecated in ggplot2 4.0.0.
## ℹ Please use `broom::augment(<lm>)` instead.
## ℹ The deprecated feature was likely used in the ggfortify package.
##   Please report the issue at <https://github.com/sinhrks/ggfortify/issues>.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## ℹ The deprecated feature was likely used in the ggfortify package.
##   Please report the issue at <https://github.com/sinhrks/ggfortify/issues>.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 48 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Removed 48 rows containing missing values or values outside the scale range
## (`geom_line()`).

  • Residuals show no strong systematic pattern.
  • The Q–Q plot shows moderate normality departures, but no compelling reason to transform this balanced example.
  • Residual spread varies somewhat without a pronounced funnel.
  • Independence depends on the experimental design and cannot be checked from these plots alone.

1.8 Model results

# Test the main effects and the diet-by-supplement interaction.
anova(model_cow)
## Analysis of Variance Table
## 
## Response: gain
##                 Df  Sum Sq Mean Sq F value    Pr(>F)    
## diet             2 287.171 143.586 83.5201 2.999e-14 ***
## supplement       3  91.881  30.627 17.8150 2.952e-07 ***
## diet:supplement  6   3.406   0.568  0.3302    0.9166    
## Residuals       36  61.890   1.719                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
  • There is no evidence of an interaction (\(F_{6,36}=0.330\), \(p=0.917\)).
  • Diet (\(F_{2,36}=83.52\), \(p<0.001\)) and supplement (\(F_{3,36}=17.82\), \(p<0.001\)) explain variation in gain.
  • The pattern is consistent with additive effects, a nonsignificant interaction does not prove the effects are identical across diets.
# Coefficients are contrasts with barley and control as references.
summary(model_cow)
## 
## Call:
## lm(formula = gain ~ diet * supplement, data = growth.moo)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -2.48756 -1.00368 -0.07452  1.03496  2.68069 
## 
## Coefficients:
##                                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                   23.2966499  0.6555863  35.536  < 2e-16 ***
## dietoats                      -2.8029851  0.9271390  -3.023  0.00459 ** 
## dietwheat                     -5.8911317  0.9271390  -6.354 2.34e-07 ***
## supplementagrimore             3.0518277  0.9271390   3.292  0.00224 ** 
## supplementsupergain           -0.8305263  0.9271390  -0.896  0.37631    
## supplementsupersupp            2.2786527  0.9271390   2.458  0.01893 *  
## dietoats:supplementagrimore   -0.2471088  1.3111726  -0.188  0.85157    
## dietwheat:supplementagrimore  -0.8182729  1.3111726  -0.624  0.53651    
## dietoats:supplementsupergain  -0.0001351  1.3111726   0.000  0.99992    
## dietwheat:supplementsupergain  0.4374395  1.3111726   0.334  0.74060    
## dietoats:supplementsupersupp  -0.9120830  1.3111726  -0.696  0.49113    
## dietwheat:supplementsupersupp -0.0158299  1.3111726  -0.012  0.99043    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.311 on 36 degrees of freedom
## Multiple R-squared:  0.8607, Adjusted R-squared:  0.8182 
## F-statistic: 20.22 on 11 and 36 DF,  p-value: 3.295e-12
  • The intercept (23.297) is the barley-control mean.
  • Diet coefficients compare diets at the control supplement, supplement coefficients compare supplements within barley.
  • Interaction coefficients measure differences in those contrasts.
  • The model has \(R^2=0.861\) and adjusted \(R^2=0.818\).

1.9 Final interaction plot

# Recalculate each treatment mean and its standard error for the final plot.
sumMoo <- growth.moo %>%
  group_by(diet, supplement) %>%
  summarise(
    meanGrow = mean(gain),
    seGrow = sd(gain)/sqrt(n())
  )
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by diet and supplement.
## ℹ Output is grouped by diet.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(diet, supplement))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
# Add error bars.
ggplot(sumMoo, aes(x = supplement, y = meanGrow,
                   colour = diet, group = diet)) +
  geom_point(size = 2.5) +
  geom_line() +
  geom_errorbar(aes(ymin = meanGrow - seGrow, ymax = meanGrow + seGrow),
                width = 0.1) +
  scale_colour_brewer(palette = "Dark2") +
  labs(x = "Supplement", y = "Mean weight gain", colour = "Diet",
       caption = "Means ± 1 standard error; four cows per treatment combination.") +
  theme_get()

2. ANCOVA: limpet egg production

2.1 Preparation

# Load the data
limp <- read.csv("/Users/aaronsi/Documents/Documents - Aaron’s MacBook Pro/4259A/data/limpet.csv")

# Set spring as the reference season.
limp$SEASON <- factor(limp$SEASON, levels = c("spring", "summer"))

# Check the data
glimpse(limp)
## Rows: 24
## Columns: 3
## $ DENSITY <int> 8, 8, 8, 8, 8, 8, 15, 15, 15, 15, 15, 15, 30, 30, 30, 30, 30, …
## $ SEASON  <fct> spring, spring, spring, summer, summer, summer, spring, spring…
## $ EGGS    <dbl> 2.875, 2.625, 1.750, 2.125, 1.500, 1.875, 2.600, 1.866, 2.066,…

2.2 Data exploration

# Check missing values, response range, and density overlap between seasons.
colSums(is.na(limp))
## DENSITY  SEASON    EGGS 
##       0       0       0
summary(limp$EGGS)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.3560  0.9165  1.4330  1.4717  1.9227  2.8750
with(limp, table(DENSITY, SEASON))
##        SEASON
## DENSITY spring summer
##      8       3      3
##      15      3      3
##      30      3      3
##      45      3      3
  • There are no missing values.
  • Both seasons have three observations at each of the same four densities.
  • Density is the only continuous predictor, so no predictor correlation matrix is needed.
  • The scatterplot below checks linearity, unusual observations, and seasonal differences before modelling.
# Plot the raw observations.
obs <- ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) + 
  geom_point() +
  scale_colour_manual(values = c(spring = "lightblue", summer = "orange")) +
  labs(x = "Limpet density", y = "Egg production", colour = "Season") +
  theme_get()

ggplotly(obs)
  • Egg production declines with density in both seasons, with spring generally higher than summer.
  • The relationships appear roughly linear with similar slopes.

2.3 Fit the model and check assumptions

  • The interaction null hypothesis is that the density slope is the same in spring and summer.
# Fit density, season, and their interaction.
limp.mod <- lm(EGGS ~ DENSITY * SEASON, data = limp)

# List the components stored in the fitted model, such as coefficients and residuals.
names(limp.mod)
##  [1] "coefficients"  "residuals"     "effects"       "rank"         
##  [5] "fitted.values" "assign"        "qr"            "df.residual"  
##  [9] "contrasts"     "xlevels"       "call"          "terms"        
## [13] "model"
# Check residual patterns, approximate normality, equal variance, and leverage.
autoplot(limp.mod, smooth.colour = NA)
## Warning: Removed 24 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Removed 24 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Removed 24 rows containing missing values or values outside the scale range
## (`geom_line()`).

  • The residual plots show no strong curvature or pronounced funnel, and the Q–Q plot is reasonably close to a straight line.
  • There is no obvious severe outlier. The diagnostics support using the linear model.
  • The analysis assumes independent experimental observations.

2.4 Model results

# The interaction tests whether the slopes differ between seasons.
anova(limp.mod)
## Analysis of Variance Table
## 
## Response: EGGS
##                Df Sum Sq Mean Sq F value    Pr(>F)    
## DENSITY         1 5.0241  5.0241 30.1971 2.226e-05 ***
## SEASON          1 3.2502  3.2502 19.5350 0.0002637 ***
## DENSITY:SEASON  1 0.0118  0.0118  0.0711 0.7925333    
## Residuals      20 3.3275  0.1664                      
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
  • There is no evidence of different slopes (\(F_{1,20}=0.0711\), \(p=0.793\)).
  • The sequential tests show effects of density (\(F_{1,20}=30.20\), \(p<0.001\)) and season (\(F_{1,20}=19.54\), \(p<0.001\)).
  • These results are consistent with additive effects.
# Display coefficient estimates, standard errors, t tests, and model fit.
summary(limp.mod)
## 
## Call:
## lm(formula = EGGS ~ DENSITY * SEASON, data = limp)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.65468 -0.25021 -0.03318  0.28335  0.57532 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)           2.664166   0.234118  11.380 3.45e-10 ***
## DENSITY              -0.033650   0.008259  -4.074 0.000591 ***
## SEASONsummer         -0.812282   0.331092  -2.453 0.023450 *  
## DENSITY:SEASONsummer  0.003114   0.011680   0.267 0.792533    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.4079 on 20 degrees of freedom
## Multiple R-squared:  0.7135, Adjusted R-squared:  0.6705 
## F-statistic:  16.6 on 3 and 20 DF,  p-value: 1.186e-05
  • The fitted equations are:

\[\widehat{EGGS}_{spring}=2.66417-0.03365\,DENSITY\] \[\widehat{EGGS}_{summer}=1.85188-0.03054\,DENSITY.\]

  • Summer’s intercept and slope are obtained by adding the summer contrasts to the spring coefficients.
  • Intercepts refer to density zero, outside the observed range.
  • The model explains 71.35% of the variation (adjusted \(R^2=0.6705\)).
  • The slope difference is not significant.

2.5 Predictions

# An example showing how expand.grid() combines values.
expand.grid(FIRST = c("A", "B"), SECOND = c(1,2))
##   FIRST SECOND
## 1     A      1
## 2     B      1
## 3     A      2
## 4     B      2
# Predict mean egg production at the density and season of each original row.
predict(limp.mod)
##         1         2         3         4         5         6         7         8 
## 2.3949692 2.3949692 2.3949692 1.6075953 1.6075953 1.6075953 2.1594217 2.1594217 
##         9        10        11        12        13        14        15        16 
## 2.1594217 1.3938428 1.3938428 1.3938428 1.6546769 1.6546769 1.6546769 0.9358016 
##        17        18        19        20        21        22        23        24 
## 0.9358016 0.9358016 1.1499321 1.1499321 1.1499321 0.4777604 0.4777604 0.4777604
# Create ten evenly spaced density values between the observed limits.
new.x <- expand.grid(DENSITY =
                       seq(from = 8, to = 45, length.out = 10))

# Displays the first six rows to check the result.
head(new.x)
##    DENSITY
## 1  8.00000
## 2 12.11111
## 3 16.22222
## 4 20.33333
## 5 24.44444
## 6 28.55556
# Combine the ten density values with both season levels.
# This replaces new.x with 20 predictor combinations for the two fitted lines.
limp$SEASON <- factor(limp$SEASON)

new.x <- expand.grid(
  DENSITY = seq(from = 8, to = 45, length.out = 10),
  SEASON = levels(limp$SEASON))

# Displays the first six rows to check the result.
head(new.x)
##    DENSITY SEASON
## 1  8.00000 spring
## 2 12.11111 spring
## 3 16.22222 spring
## 4 20.33333 spring
## 5 24.44444 spring
## 6 28.55556 spring
# Calculate fitted means and their 95% confidence intervals.
new.y <- predict(limp.mod, newdata = new.x,
                 interval = 'confidence')

# Displays the first six rows to check the result.
head(new.y)
##        fit      lwr      upr
## 1 2.394969 2.019285 2.770654
## 2 2.256632 1.931230 2.582034
## 3 2.118294 1.834274 2.402315
## 4 1.979957 1.724062 2.235852
## 5 1.841619 1.595998 2.087241
## 6 1.703282 1.447918 1.958646
# Combine predictor values with their fitted means and confidence limits.
addThese <- data.frame(new.x, new.y)

# Rename fit to EGGS so the prediction data match the original plot mapping.
addThese <- rename(addThese, EGGS = fit)

# Displays the first six rows to check the result.
head(addThese)
##    DENSITY SEASON     EGGS      lwr      upr
## 1  8.00000 spring 2.394969 2.019285 2.770654
## 2 12.11111 spring 2.256632 1.931230 2.582034
## 3 16.22222 spring 2.118294 1.834274 2.402315
## 4 20.33333 spring 1.979957 1.724062 2.235852
## 5 24.44444 spring 1.841619 1.595998 2.087241
## 6 28.55556 spring 1.703282 1.447918 1.958646
# Create one prediction per season at the overall mean density.
new.x2 <- expand.grid(DENSITY = mean(limp$DENSITY),
                     SEASON = levels(limp$SEASON))

# Keep this in new.x2 so the full plotting grid in new.x is preserved.
predEgg <- predict(limp.mod, newdata = new.x2)

EggAtMeanDens <- data.frame(new.x2, predEgg)

# Displays the first six rows to check the result.
head(EggAtMeanDens)
##   DENSITY SEASON predEgg
## 1    24.5 spring 1.83975
## 2    24.5 summer 1.10375
  • At mean density (24.5), predicted egg production is 1.83975 in spring and 1.10375 in summer.

2.6 Final fitted plot

# Overlay the model predictions and confidence bands on the raw observations.
# stat = "identity" uses our calculated fit, lwr, and upr values directly
limpet_plot <- ggplot(limp, aes(x = DENSITY, y = EGGS, colour = SEASON)) + 
  geom_point(size = 3) + 
  geom_smooth(data = addThese,
              aes(ymin = lwr, ymax = upr,
                  fill = SEASON), stat = 'identity') + 
  scale_colour_manual(values = c(spring = "#0072B2", summer = "#D55E00")) + 
  scale_fill_manual(values = c(spring = "#0072B2", summer = "#D55E00")) +
  labs(x = "Limpet density", y = "Egg production",
       colour = "Season", fill = "Season",
       caption = "Fitted means with pointwise 95% confidence bands.") +
  theme_get()

ggplotly(limpet_plot)
  • The shaded bands describe uncertainty in mean egg production, not prediction intervals for individual observations.