Chapter 6: Trend Analysis

R Code and Instructions

Scott E. Maxwell, Harold D. Delaney, and Ken Kelley

Code
Results
On this page

Examples follow the book’s section numbers.

Chapter 6 moves from qualitative categories to quantitative factors, where the groups differ in amount rather than in kind. Bridging the analysis of variance of Chapters 3–5 with regression, the chapter shows how to estimate and test a linear trend, how to test for nonlinearity as a whole, and how orthogonal polynomials isolate higher order shapes such as the quadratic and the cubic.

These notes build on Chapter 1 and Chapters 3–5, where the operational aspects of R and the AMCP data sets are introduced; here we skip details already covered there. This chapter uses one data set, chapter_6_table_1, the hypothetical memory data of Table 6.1.

HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(dplyr)          # data manipulation
library(ggplot2)        # figures
library(DMAR)           # design, measurement, and analysis
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables

6.4 — Statistical Treatment of Trend Analysis

The data of Table 6.1

The data of Table 6.1 are recall scores for 24 children, six in each of four study-time conditions: 1, 2, 3, or 4 minutes to study a list of 12 words. The dependent variable is the number of words recalled after a brief interference task. The quantitative factor here is “minutes allowed for study,” so the numbers 1 through 4 carry meaning; they are not arbitrary labels as the four hypertension treatments of Chapter 4 were.

The data come from the AMCP package, loaded above.

HideShow
data(chapter_6_table_1)
chapter_6_table_1
HideShow
   Recall Minutes
1       2       1
2       3       1
3       1       1
4       2       1
5       0       1
6       4       1
7       6       2
8       8       2
9       5       2
10      3       2
11      7       2
12      7       2
13      6       3
14      8       3
15     10       3
16      5       3
17     10       3
18      9       3
19     11       4
20     10       4
21      7       4
22      9       4
23      8       4
24      9       4

The four group means are the quantities every later calculation rests on.

HideShow
Summary_Recall <- chapter_6_table_1 |>
  group_by(Minutes) |>
  summarize(mean_Recall = mean(Recall),
            sd_Recall   = sd(Recall),
            n_Recall    = n(),
            .groups     = "drop")
Summary_Recall
HideShow
# A tibble: 4 × 4
  Minutes mean_Recall sd_Recall n_Recall
    <int>       <dbl>     <dbl>    <int>
1       1           2      1.41        6
2       2           6      1.79        6
3       3           8      2.10        6
4       4           9      1.41        6
HideShow
#> means 2, 6, 8, 9 — matches book p. 271, Table 6.1
Shared objects for the figures

The figures in this chapter all build from the recall data together with the linear and quadratic trend models the chapter fits to it. We set up those shared objects once here so each figure can refer to them: the fitted models, the group (cell) means with their model-predicted values, and the per-person residuals from each model.

HideShow
d6 <- chapter_6_table_1

# The two trend models the chapter fits to the recall data.
lin_fit  <- lm(Recall ~ Minutes, data = d6)                 # Eq. 6.23: 0.50 + 2.3 X
quad_fit <- lm(Recall ~ Minutes + I(Minutes^2), data = d6)  # Eq. 6.24

# Group (cell) means at each study time, and the model-predicted means.
group_means <- d6 |>
  group_by(Minutes) |>
  summarize(Recall = mean(Recall), .groups = "drop")
group_means$pred_lin  <- predict(lin_fit,  newdata = group_means)
group_means$pred_quad <- predict(quad_fit, newdata = group_means)

# Residuals (actual minus predicted) for every participant, for both models.
d6 <- d6 |>
  mutate(resid_lin  = Recall - predict(lin_fit,  newdata = d6),
         resid_quad = Recall - predict(quad_fit, newdata = d6))
Figure 6.1. Scatterplot of recall scores as a function of study time

A scatterplot of the 24 recall scores as a function of study time, the raw data of Table 6.1. The upward drift of the points motivates fitting a linear trend: on the whole, more study time goes with more words recalled.

HideShow
ggplot(d6, aes(Minutes, Recall)) +
  geom_point(shape = 4, size = 2.6, stroke = 0.9) +
  scale_x_continuous(breaks = 1:4) +
  scale_y_continuous(limits = c(0, 12), breaks = 0:12) +
  labs(title = "Figure 6.1. Scatterplot of recall scores as a function of study time",
       x = "Study time (minutes allotted)", y = "Recall (number of words)")
Figure 6.1. Scatterplot of recall scores as a function of study time.

Figure 6.1. Scatterplot of recall scores as a function of study time.

Two analyses of the same data

To see what the quantitative nature of the factor buys, run two different models on exactly the same data.

The first is the standard one-way ANOVA. It ignores the ordering of Minutes, treating it as four unordered categories, and asks only whether any group differs from another. Its mean square within is the error term the book uses for every trend test in this chapter, so we keep the object around.

HideShow
ANOVA_Object <- aov(Recall ~ as.factor(Minutes), data = chapter_6_table_1)
ANOVA_Result <- anova(ANOVA_Object)
ANOVA_Result
HideShow
Analysis of Variance Table

Response: Recall
                   Df Sum Sq Mean Sq F value    Pr(>F)    
as.factor(Minutes)  3  172.5    57.5  19.828 3.306e-06 ***
Residuals          20   58.0     2.9                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> SS_B = 172.5, SS_W = 58.0, MS_W = 2.9 — matches book p. 281 and Table 6.3, p. 285

The second treats Minutes as the number it is and fits a straight line, which is the model of Equation 6.2. The regression output reports the estimated slope β̂1\hat\beta_1 and intercept β̂0\hat\beta_0 directly.

HideShow
Regression_Object <- lm(Recall ~ Minutes, data = chapter_6_table_1)
Regression_Result <- summary(Regression_Object)
Regression_Result
HideShow

Call:
lm(formula = Recall ~ Minutes, data = chapter_6_table_1)

Residuals:
   Min     1Q Median     3Q    Max 
-2.800 -1.475  0.050  1.375  2.900 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   0.5000     0.9033   0.554    0.585    
Minutes       2.3000     0.3298   6.973 5.33e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.807 on 22 degrees of freedom
Multiple R-squared:  0.6885,    Adjusted R-squared:  0.6743 
F-statistic: 48.63 on 1 and 22 DF,  p-value: 5.333e-07
HideShow
#> intercept 0.50, slope 2.30 — matches book p. 274

6.4.1 — The Slope Parameter

Equation 6.7 says that the estimated slope is just the linear contrast of the group means divided by the sum of the squared contrast coefficients, where the coefficients of Equation 6.8 are cj=Xj−X‾c_j = X_j – \bar{X}. That is worth doing by hand once, because it makes the point that a “linear trend” in ANOVA is the slope of a simple regression.

HideShow
# Equation 6.8: the c-weights are deviations of X from its mean.
Summary_Recall$c_weight <- Summary_Recall$Minutes - mean(chapter_6_table_1$Minutes)
Summary_Recall
HideShow
# A tibble: 4 × 5
  Minutes mean_Recall sd_Recall n_Recall c_weight
    <int>       <dbl>     <dbl>    <int>    <dbl>
1       1           2      1.41        6     -1.5
2       2           6      1.79        6     -0.5
3       3           8      2.10        6      0.5
4       4           9      1.41        6      1.5
HideShow
#> c-weights -1.5, -0.5, 0.5, 1.5 — matches book p. 274

mean(chapter_6_table_1$Minutes)
HideShow
[1] 2.5
HideShow
#> 2.5 — matches book p. 274 (the mean study time, X-bar)

6.4.2 — Numerical Example

With the coefficients in hand, Equation 6.6 gives the linear contrast and Equation 6.7 turns it into the slope.

HideShow
C_Linear <- Summary_Recall$c_weight
MS_W     <- ANOVA_Result$"Mean Sq"[2]
  # MS_W comes from the cell means ("as.factor") ANOVA rather than from the error of the
  # straight-line `lm` model. The book explains on p. 276 why that is the recommended
  # denominator for a trend test when the factor has few distinct values.

# Equation 6.6
Psi_Linear <- sum(Summary_Recall$mean_Recall * C_Linear)
Psi_Linear
HideShow
[1] 11.5
HideShow
#> 11.5 — matches book p. 274 (psi_hat_linear = -1.5(2) - 0.5(6) + 0.5(8) + 1.5(9) = 11.5)

Sum_c_Squared <- sum(C_Linear^2)
Sum_c_Squared
HideShow
[1] 5
HideShow
#> 5.0 — matches book p. 274 (sum of squared c-weights)

# Equation 6.7
b1 <- Psi_Linear / Sum_c_Squared
b1
HideShow
[1] 2.3
HideShow
#> 2.3 — matches book p. 274 (slope = 11.5 / 5.0 = 2.3)

With the slope known, the least squares intercept completes the equation of the line.

HideShow
b0 <- mean(chapter_6_table_1$Recall) - b1 * mean(chapter_6_table_1$Minutes)
b0
HideShow
[1] 0.5
HideShow
#> 0.50 — matches book p. 274 (intercept = 6.25 - 2.3 * 2.5 = 0.50)

Every additional minute of study time is estimated to translate into an average gain of 2.3 additional words recalled. The fitted line is Ŷij=0.50+2.3Xj\hat{Y}_{ij} = 0.50 + 2.3X_j.

Figure 6.2. Sample means and estimated linear trend

The book’s Figure 6.2 plots two sets of points at each study time: the sample mean (open circles) and the mean predicted by the linear trend (filled circles), with the fitted line through the predicted means. The line passes near but not exactly through the sample means, which rise quickly from 1 to 2 minutes and then level off.

HideShow
fig_6_2_points <- rbind(
  data.frame(Minutes = group_means$Minutes, Value = group_means$Recall,
             Kind = "Sample mean"),
  data.frame(Minutes = group_means$Minutes, Value = group_means$pred_lin,
             Kind = "Predicted mean")
)
fig_6_2_points$Kind <- factor(fig_6_2_points$Kind,
                              levels = c("Sample mean", "Predicted mean"))

ggplot(fig_6_2_points, aes(Minutes, Value, shape = Kind, color = Kind)) +
  geom_abline(intercept = coef(lin_fit)[1], slope = coef(lin_fit)[2],
              color = "#0C2340", linewidth = 0.8) +
  geom_point(size = 3.6, stroke = 1) +
  scale_shape_manual(name = NULL, values = c("Sample mean" = 1, "Predicted mean" = 16)) +
  scale_color_discrete(name = NULL) +
  scale_x_continuous(breaks = 1:4) +
  scale_y_continuous(limits = c(0, 12), breaks = 0:12) +
  labs(title = "Figure 6.2. Sample means and estimated linear trend",
       x = "Study time (minutes allotted)", y = "Recall (number of words)") +
  theme(legend.position = "top")
Figure 6.2. Plot of sample means and estimated linear trend.

Figure 6.2. Plot of sample means and estimated linear trend.

6.4.3 — Hypothesis Test of Slope Parameter

The book frames the test of β1=0\beta_1 = 0 as a model comparison: the full model is the straight line of Equation 6.2 and the restricted model drops the slope (Equation 6.9). Base R carries that comparison out directly, and the resulting ER−EFE_R – E_F is exactly the sum of squares of the linear contrast promised by Equation 6.11.

HideShow
Model_Restricted <- lm(Recall ~ 1,       data = chapter_6_table_1)  # Equation 6.9
Model_Full       <- lm(Recall ~ Minutes, data = chapter_6_table_1)  # Equation 6.2
anova(Model_Restricted, Model_Full)
HideShow
Analysis of Variance Table

Model 1: Recall ~ 1
Model 2: Recall ~ Minutes
  Res.Df   RSS Df Sum of Sq      F    Pr(>F)    
1     23 230.5                                  
2     22  71.8  1     158.7 48.627 5.333e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#> Sum of Sq = 158.7 (= E_R - E_F = SS_linear) — matches book p. 277

The FF reported on that line (48.63) uses the straight-line model’s own error term, which is the usual choice in regression. As the book explains on p. 276, in ANOVA we instead divide by MSWMS_W from the cell means model, which is what gives the FF reported throughout the chapter.

HideShow
SS_Linear <- Psi_Linear^2 / sum(C_Linear^2 / Summary_Recall$n_Recall)
SS_Linear
HideShow
[1] 158.7
HideShow
#> 158.7 — matches book p. 277 (SS_linear = 6(11.5)^2 / 5 = 158.7)

F_Linear <- SS_Linear / MS_W
F_Linear
HideShow
[1] 54.72414
HideShow
#> 54.72 — matches book p. 277 (F = 158.7 / 2.9 = 54.72)

The linear trend is statistically significant, F(1,20)=54.72F(1, 20) = 54.72: recall increased linearly as study time increased.

6.5 — Confidence Interval and Other Effect Size Measures for the Slope Parameter

Equation 6.12 gives the confidence interval for the slope,

β̂1±Fα;1,N−aMSW∑j=1a(cj2/nj)∑j=1acj2,\hat\beta_1 \pm \sqrt{F_{\alpha;1,N-a}}\;\frac{\sqrt{MS_W \sum_{j=1}^{a} (c_j^2/n_j)}}{\sum_{j=1}^{a} c_j^2},

which differs from the Chapter 4 interval for a contrast only by the rescaling that turns ψ̂\hat\psi into β̂1\hat\beta_1. That rescaling is the whole practical difficulty: an interval computed from the raw coefficients −1.5,−0.5,0.5,1.5-1.5, -0.5, 0.5, 1.5 is an interval for ψ\psi, not for β1\beta_1, and the two differ by a factor of ∑cj2\sum c_j^2.

6.5.1 — Numerical Example

The test, from the book’s own inputs

The book’s Section 6.5.1 recomputes the linear trend test from n=6n = 6, the four means, and ∑cj2=5\sum c_j^2 = 5. Scaling the weights first (dividing each by ∑cj2\sum c_j^2) makes the contrast itself equal the slope, and the sum of squares is unchanged, because rescaling a contrast’s coefficients does not change its sum of squares.

HideShow
c_Linear        <- Summary_Recall$Minutes - mean(chapter_6_table_1$Minutes)
c_Linear_Scaled <- c_Linear / sum(c_Linear^2)
c_Linear_Scaled
HideShow
[1] -0.3 -0.1  0.1  0.3
HideShow
#> -0.3, -0.1, 0.1, 0.3 — matches book p. 278 (the scaling needed for an interval on beta_1)

Ybar <- Summary_Recall$mean_Recall
n_j  <- Summary_Recall$n_Recall

Slope_From_Contrast <- sum(c_Linear_Scaled * Ybar)
Slope_From_Contrast
HideShow
[1] 2.3
HideShow
#> 2.3 — matches book p. 274 (the scaled contrast is the slope itself)

SS_Linear_Scaled <- Slope_From_Contrast^2 / sum(c_Linear_Scaled^2 / n_j)
SS_Linear_Scaled
HideShow
[1] 158.7
HideShow
#> 158.7 — matches book p. 277 (the SS is invariant to rescaling the c-weights)

F_value <- SS_Linear_Scaled / MS_W
F_value
HideShow
[1] 54.72414
HideShow
#> 54.72 — matches book p. 277 and Table 6.3, p. 285

This is significant well beyond the .001 level, so we can assert a linear trend in the population.

The confidence interval by hand, from Equation 6.12

The hypothesis test says the slope is not zero but gives no plausible range for it. The book works the interval out by hand on p. 278, and the same arithmetic in base R gives each intermediate value it reports.

HideShow
# Critical F with 1 and N - a = 20 degrees of freedom.
F_Critical <- qf(0.95, df1 = 1, df2 = 20)
F_Critical
HideShow
[1] 4.351244
HideShow
#> 4.35 — matches book p. 278 (F_.05;1,20 = 4.35)

# Standard error of the slope: the Equation 6.12 radical divided by sum(c^2).
SE_Slope <- sqrt(MS_W * sum(C_Linear^2 / Summary_Recall$n_Recall)) / sum(C_Linear^2)
SE_Slope
HideShow
[1] 0.3109126
HideShow
#> 0.3109 — matches book p. 278 (standard error of the slope)

# Half-width (margin of error) and the interval itself.
Half_Width <- sqrt(F_Critical) * SE_Slope
Half_Width
HideShow
[1] 0.6485524
HideShow
#> 0.65 — matches book p. 278 (half width = sqrt(4.35) * 0.3109)

c(Lower = b1 - Half_Width, Upper = b1 + Half_Width)
HideShow
   Lower    Upper 
1.651448 2.948552 
HideShow
#> [1.65, 2.95] — matches book p. 278 (95% CI on the slope)

Every additional minute of study time leads to an increase of between 1.65 and 2.95 words recalled.

Intervals for the contrast and the slope in DMAR

With the original contrast weights, ci_c() gives an interval for the contrast ψ\psi. Dividing the weights by ∑cj2=5\sum c_j^2 = 5 gives the interval for the slope β1\beta_1, in words recalled per minute of study.

HideShow
ci_c(means = Summary_Recall$mean_Recall,
     s_anova = sqrt(MS_W),
     c_weights = Summary_Recall$c_weight,
     n_per_group = Summary_Recall$n_Recall,
     N = sum(Summary_Recall$n_Recall),
     conf_level = 0.95)
term value
ci_lower 8.257
contrast 11.500
ci_upper 14.743

Confidence level: 95%

HideShow
#> contrast 11.500, 95% CI [8.257, 14.743]

Using the scaled weights gives the interval for β1\beta_1.

HideShow
ci_c(means = Summary_Recall$mean_Recall,
     s_anova = sqrt(MS_W),
     c_weights = Summary_Recall$c_weight / sum(Summary_Recall$c_weight^2),
     n_per_group = Summary_Recall$n_Recall,
     N = sum(Summary_Recall$n_Recall),
     conf_level = 0.95)
term value
ci_lower 1.651
contrast 2.300
ci_upper 2.949

Confidence level: 95%

HideShow
#> slope 2.300, 95% CI [1.651, 2.949] — matches book p. 278 (2.3, [1.65, 2.95])

Finally, to guard against the misconception the book flags on p. 278: a significant linear trend does not imply the relationship is strictly a straight line. The data may go up and curve while doing so. The FF of 54.72 tells us it goes up; it says nothing about curvature. For that we test nonlinearity.

6.6 — Testing for Nonlinearity

Before testing specific shapes, Section 6.6 asks the broader question: is there any nonlinearity? Equation 6.18 pools every non-linear trend into a single test,

F=(SSB−SSlinear)/(a−2)MSW.F = \frac{(SS_B – SS_{linear})/(a – 2)}{MS_W}.

As a model comparison, that is the straight-line model (restricted) against the cell means model (full), which base R does in one call.

HideShow
Model_Linear     <- lm(Recall ~ Minutes,         data = chapter_6_table_1)  # Eq. 6.2
Model_Cell_Means <- lm(Recall ~ factor(Minutes), data = chapter_6_table_1)  # cell means
anova(Model_Linear, Model_Cell_Means)
HideShow
Analysis of Variance Table

Model 1: Recall ~ Minutes
Model 2: Recall ~ factor(Minutes)
  Res.Df  RSS Df Sum of Sq      F Pr(>F)
1     22 71.8                           
2     20 58.0  2      13.8 2.3793 0.1183
HideShow
#> Sum of Sq = 13.8, F = 2.38, p = .118 — matches book p. 281 and Table 6.3, p. 285

6.6.1 — Numerical Example

The book works the same test from its component sums of squares, which the ANOVA above already gave us.

HideShow
SS_Between <- ANOVA_Result$"Sum Sq"[1]
SS_Between
HideShow
[1] 172.5
HideShow
#> 172.5 — matches book p. 281

SS_Departure <- SS_Between - SS_Linear
SS_Departure
HideShow
[1] 13.8
HideShow
#> 13.8 — matches book Table 6.3, p. 285 (deviation from linearity, SS_B - SS_linear)

df_Departure <- 2   # a - 2 = 4 - 2
MS_Departure <- SS_Departure / df_Departure
MS_Departure
HideShow
[1] 6.9
HideShow
#> 6.9 — matches book Table 6.3, p. 285

F_Departure <- MS_Departure / MS_W
F_Departure
HideShow
[1] 2.37931
HideShow
#> 2.38 — matches book p. 281 (F = (172.5 - 158.7)/2 / 2.9 = 2.38)

pf(F_Departure, df1 = df_Departure, df2 = 20, lower.tail = FALSE)
HideShow
[1] 0.1183138
HideShow
#> .118 — matches book Table 6.3, p. 285 (deviation from linearity, p)

With 2 and 20 degrees of freedom this is not significant at the .05 level, so the apparent nonlinearity in Figure 6.2 may simply reflect sampling error. As always, that is a failure to reject, not a demonstration that the nonlinear trends are zero.

This omnibus test can also obscure a real effect: pooling a strong quadratic trend with a negligible cubic one dilutes the signal. Section 6.7 tests the shapes individually.

How to Cite This Page

The book. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.

This page. Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Chapter 6: Trend Analysis (R code and instructions). Companion materials for Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). https://DesigningExperiments.com

These examples use DMAR 1.2.0. The printed book predates DMAR.

References

Scroll to Top