R Code and Instructions
On this page
- 6.4 — Statistical Treatment of Trend Analysis
- 6.4.1 — The Slope Parameter
- 6.4.2 — Numerical Example
- 6.4.3 — Hypothesis Test of Slope Parameter
- 6.5 — Confidence Interval and Other Effect Size Measures for the Slope Parameter
- 6.5.1 — Numerical Example
- 6.6 — Testing for Nonlinearity
- 6.6.1 — Numerical Example
- 6.7 — Testing Individual Higher Order Trends
- 6.7.1 — Contrast Coefficients for Higher Order Trends
- 6.7.2 — Numerical Example
- 6.8 — Further Examination of Nonlinear Trends
- How to Cite This Page
- References
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 tables6.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
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 4The four group means are the quantities every later calculation rests on.
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 6Figure 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.
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
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 ' ' 1The 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 and intercept directly.
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-076.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 . 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
# 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.5HideShow
[1] 2.56.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_LinearHideShow
[1] 11.5HideShow
[1] 5HideShow
[1] 2.3With the slope known, the least squares intercept completes the equation of the line.
HideShow
[1] 0.5Every additional minute of study time is estimated to translate into an average gain of 2.3 additional words recalled. The fitted line is .
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.
6.4.3 — Hypothesis Test of Slope Parameter
The book frames the test of 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 is exactly the sum of squares of the linear contrast promised by Equation 6.11.
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 ' ' 1The 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 from the cell means model, which is what gives the reported throughout the chapter.
HideShow
[1] 158.7HideShow
[1] 54.72414The linear trend is statistically significant, : 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,
which differs from the Chapter 4 interval for a contrast only by the rescaling that turns into . That rescaling is the whole practical difficulty: an interval computed from the raw coefficients is an interval for , not for , and the two differ by a factor of .
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 , the four means, and . Scaling the weights first (dividing each by ) 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
[1] -0.3 -0.1 0.1 0.3HideShow
[1] 2.3HideShow
[1] 158.7HideShow
[1] 54.72414This 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
[1] 4.351244HideShow
[1] 0.3109126HideShow
[1] 0.6485524HideShow
Lower Upper
1.651448 2.948552 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 .
Dividing the weights by gives the interval for the slope , in words recalled per minute of
study.
| term | value |
|---|---|
| ci_lower | 8.257 |
| contrast | 11.500 |
| ci_upper | 14.743 |
Confidence level: 95%
Using the scaled weights gives the interval for .
| term | value |
|---|---|
| ci_lower | 1.651 |
| contrast | 2.300 |
| ci_upper | 2.949 |
Confidence level: 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 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,
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
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.11836.6.1 — Numerical Example
The book works the same test from its component sums of squares, which the ANOVA above already gave us.
HideShow
[1] 172.5HideShow
[1] 13.8HideShow
[1] 6.9HideShow
[1] 2.37931HideShow
[1] 0.1183138With 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.
6.7 — Testing Individual Higher Order Trends
6.7.1 — Contrast Coefficients for Higher Order Trends
Appendix Table A.10 lists contrast coefficients for trend analysis when the levels of are equally spaced and the group sizes are equal. For four groups they are (linear), (quadratic), and (cubic).
In base R, contr.poly() generates the same set of
contrasts. For levels,
contr.poly(j) returns a matrix whose columns are the linear
(.L), quadratic (.Q), and cubic
(.C) trends.
HideShow
.L .Q .C
[1,] -0.6708204 0.5 -0.2236068
[2,] -0.2236068 -0.5 0.6708204
[3,] 0.2236068 -0.5 -0.6708204
[4,] 0.6708204 0.5 0.2236068The signs in each column show the shape being tested:
- Linear (
.L): runs from negative to positive, so it detects a straight line. - Quadratic (
.Q): high, low, low, high, so it detects a single bend (a U). - Cubic (
.C): changes direction twice, so it detects an S shape.
The numbers themselves differ from Table A.10 because
contr.poly() normalizes each column to unit length, whereas
the book uses integers for readability. The two are proportional, and as
the book notes on p. 284, multiplying all coefficients of a contrast by
a constant changes neither the sum of squares nor the . The metric does matter for a
confidence interval, which is why the scaling mattered so much in
Section 6.5.1.
The same contrasts in DMAR
DMAR’s orthogonal_polynomial() adds the ability to ask
for either form. With type = "integer" it returns
exactly the integer trend weights the book uses, with a final column
reporting — the quantity
Table 6.2 needs and contr.poly() does not report. The
default type = "orthonormal" returns the rescaled weights
contr.poly() gives. Trends are shown in rows, the Table
A.10 layout; the stored object is the transpose (levels by trends),
ready to pass to contrasts().
HideShow
Orthogonal-polynomial (trend) contrasts (integer), 4 levels
Layout: trends in rows, levels in columns (MDK Table A.10); final column is sum c^2.
Stored object is the transpose (levels x trends) for contrasts().
L1 L2 L3 L4 sum c^2
linear -3 -1 1 3 20
quadratic 1 -1 -1 1 4
cubic -1 3 -3 1 20HideShow
Orthogonal-polynomial (trend) contrasts (orthonormal), 4 levels
Layout: trends in rows, levels in columns (MDK Table A.10); final column is sum c^2.
Stored object is the transpose (levels x trends) for contrasts().
L1 L2 L3 L4 sum c^2
linear -0.671 -0.224 0.224 0.671 1
quadratic 0.500 -0.500 -0.500 0.500 1
cubic -0.224 0.671 -0.671 0.224 1A trend analysis relies on the contrasts being mutually orthogonal so
that the between-group sum of squares partitions cleanly into one piece
per trend. DMAR’s is_orthogonal_set() checks that directly:
every pairwise dot product is zero and every contrast sums to zero.
| term | value |
|---|---|
| all_orthogonal | 1 |
| all_contrasts_sum_to_zero | 1 |
| n_contrasts | 3 |
| dot[linear . quadratic] | 0 |
| dot[linear . cubic] | 0 |
| dot[quadratic . cubic] | 0 |
6.7.2 — Numerical Example
Table 6.2 by hand
Table 6.2 shows the intermediate calculations behind each trend’s sum of squares, (Equation 6.11). Reproducing it in base R takes three lines.
HideShow
HideShow
Linear Quadratic Cubic
23 -3 1 HideShow
HideShow
Linear Quadratic Cubic
158.7 13.5 0.3 The partitioned ANOVA
To get the same partition from a fitted model, define
Minutes as a factor and attach the polynomial contrasts to
it. The data themselves are unchanged; the contrast attribute is visible
in the structure of the factor.
HideShow
'data.frame': 24 obs. of 3 variables:
$ Recall : int 2 3 1 2 0 4 6 8 5 3 ...
$ Minutes : int 1 1 1 1 1 1 2 2 2 2 ...
$ Minutes_factor: Factor w/ 4 levels "1","2","3","4": 1 1 1 1 1 1 2 2 2 2 ...
..- attr(*, "contrasts")= num [1:4, 1:3] -0.671 -0.224 0.224 0.671 0.5 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:4] "1" "2" "3" "4"
.. .. ..$ : chr [1:3] ".L" ".Q" ".C"Running aov() and calling summary() in the
ordinary way looks no different from before.
HideShow
Df Sum Sq Mean Sq F value Pr(>F)
Minutes_factor 3 172.5 57.5 19.83 3.31e-06 ***
Residuals 20 58.0 2.9
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The difference comes from asking summary() to
split the factor into its three single-degree-of-freedom
pieces. The between-group sum of squares of 172.5 then partitions into
linear (158.7), quadratic (13.5), and cubic (0.3). Note that the
quadratic and cubic pieces add to the deviation from linearity computed
in Section 6.6.1: , on two degrees of freedom (Equation 6.20).
HideShow
Df Sum Sq Mean Sq F value Pr(>F)
Minutes_factor 3 172.5 57.5 19.828 3.31e-06 ***
Minutes_factor: C1 1 158.7 158.7 54.724 3.82e-07 ***
Minutes_factor: C2 1 13.5 13.5 4.655 0.0433 *
Minutes_factor: C3 1 0.3 0.3 0.103 0.7511
Residuals 20 58.0 2.9
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1The partitioned ANOVA above gives five of the six rows of the book’s
Table 6.3. summary(..., split = ) reports each trend on its
own but has no pooled row, so the book’s deviation-from-linearity line —
on two degrees of freedom,
computed just above — is not among them. The same numbers read more
easily as an APA-style table. We build it with gt,
which formats sums of squares, df, , , and partial properly in HTML. The partial
for each trend equals its
from Table 6.4,
since both are .
HideShow
# Pull the partitioned ANOVA rows out of the summary object. Row labels carry
# leading whitespace (e.g. " Minutes_factor: C1"), so trim before matching.
aov_mat <- ANOVA_Split[[1]]
rn <- trimws(rownames(aov_mat))
ss_res <- aov_mat[rn == "Residuals", "Sum Sq"]
grab <- function(key) {
i <- which(rn == key)
c(SS = aov_mat[i, "Sum Sq"], df = aov_mat[i, "Df"], MS = aov_mat[i, "Mean Sq"],
Fstat = aov_mat[i, "F value"], p = aov_mat[i, "Pr(>F)"])
}
anova_tbl <- as.data.frame(rbind(
grab("Minutes_factor"),
grab("Minutes_factor: C1"),
grab("Minutes_factor: C2"),
grab("Minutes_factor: C3"),
grab("Residuals")
))
anova_tbl$Source <- c("Between (Minutes)", " Linear", " Quadratic",
" Cubic", "Within (error)")
# Partial eta-squared: each effect's share of effect-plus-error variance.
anova_tbl$peta <- ifelse(anova_tbl$Source == "Within (error)",
NA_real_, anova_tbl$SS / (anova_tbl$SS + ss_res))
# p values in the book's style: "<.001" rather than a rounded zero.
anova_tbl$p_fmt <- ifelse(is.na(anova_tbl$p), "",
ifelse(anova_tbl$p < .001, "<.001",
sub("^0", "", formatC(anova_tbl$p, format = "f", digits = 3))))
anova_tbl |>
select(Source, SS, df, MS, Fstat, p_fmt, peta) |>
gt() |>
fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
fmt_number(columns = peta, decimals = 3) |>
sub_missing(missing_text = "") |>
cols_label(Fstat = md("*F*"), p_fmt = md("*p*"),
peta = md("Partial η<sup>2</sup>")) |>
tab_header(title = md("**Table 6.3**. Analysis of Variance for Recall, with Trend Components")) |>
cols_align(align = "center", columns = -Source)| Table 6.3. Analysis of Variance for Recall, with Trend Components | ||||||
| Source | SS | df | MS | F | p | Partial η2 |
|---|---|---|---|---|---|---|
| Between (Minutes) | 172.50 | 3 | 57.50 | 19.83 | <.001 | 0.748 |
| Linear | 158.70 | 1 | 158.70 | 54.72 | <.001 | 0.732 |
| Quadratic | 13.50 | 1 | 13.50 | 4.66 | .043 | 0.189 |
| Cubic | 0.30 | 1 | 0.30 | 0.10 | .751 | 0.005 |
| Within (error) | 58.00 | 20 | 2.90 | |||
The same trend tests in DMAR
The split summary() gives the three tests but no estimates, standard
errors, or confidence intervals for the contrasts themselves. DMAR’s
contrast_test() adds exactly that: given a fitted model and
a named list of contrast weights, it returns each contrast’s estimate,
standard error, , degrees of
freedom, value (raw and
adjusted), and confidence interval. Supplying the book’s integer trend
weights tests all three trends in one call, and each reproduces the corresponding from the partitioned ANOVA above.
| contrast | estimate | se | t_value | df | p_value | p_adjusted | ci_lower | ci_upper |
|---|---|---|---|---|---|---|---|---|
| linear | 23.000 | 3.109 | 7.398 | 20 | < 0.0001 | < 0.0001 | 16.514 | 29.486 |
| quadratic | -3.000 | 1.390 | -2.158 | 20 | 0.0433 | 0.0433 | -5.900 | -0.100 |
| cubic | 1.000 | 3.109 | 0.322 | 20 | 0.7511 | 0.7511 | -5.486 | 7.486 |
Confidence level: 95%
HideShow
linear quadratic cubic
54.72 4.66 0.10 The linear trend dominates and the cubic is negligible, the same
conclusion the partitioned summary() reached, now expressed
as individual contrast tests with confidence intervals. Note also that
the standard error of the linear contrast, 3.109, is ten times the
standard error of the slope, 0.3109, reported on p. 278: the integer
weights here are ten times the scaled weights that produce .
Measures of association strength (Table 6.4)
Hypothesis tests are not the whole analysis. Table 6.4 reports three measures of association strength for each trend, the same three introduced in Chapter 4 (Equations 4.46–4.48).
HideShow
SS_Between SS_Within SS_Total
172.5 58.0 230.5 HideShow
#> 172.5 and 58.0 — matches book Table 6.3, p. 285
SS_Trends <- c(Linear = unname(SS_Trend_Manual["Linear"]),
Quadratic = unname(SS_Trend_Manual["Quadratic"]),
Cubic = unname(SS_Trend_Manual["Cubic"]))
R2_Alerting <- SS_Trends / SS_Between # Equation 4.46
R2_EffectSize <- SS_Trends / SS_Total # Equation 4.47
R2_Contrast <- SS_Trends / (SS_Trends + SS_Within) # Equation 4.48
Table_6_4 <- round(cbind(R2_Alerting, R2_EffectSize, R2_Contrast), 2)
Table_6_4HideShow
R2_Alerting R2_EffectSize R2_Contrast
Linear 0.92 0.69 0.73
Quadratic 0.08 0.06 0.19
Cubic 0.00 0.00 0.01HideShow
[1] 1The linear trend accounts for 92% of the between-group variance and 69% of the total variance; the cubic is practically nonexistent.
6.8 — Further Examination of Nonlinear Trends
The linear trend model and its errors
A continuous regression view makes clear how linear and nonlinear trends can coexist in the same data. The straight-line fit repeats the coefficients of Equation 6.23.
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-07HideShow
2.5 % 97.5 %
(Intercept) -1.373282 2.373282
Minutes 1.615974 2.984026These intervals are wider than the [1.65, 2.95] of Section 6.5.1
because they come from a different error term: confint() on
this model uses the straight-line model’s own residual mean square,
whereas the trend analysis uses from the cell means model, in which
the quadratic and cubic components are implicitly accounted for.
The coefficients match Equation 6.23, . To understand the quadratic trend, look at the errors of this linear model: the predicted mean for each group against the mean actually observed.
HideShow
time_points <- data.frame(Minutes = 1:4)
Predicted_Linear <- predict(Regression_Object, newdata = time_points)
Actual_Means <- tapply(chapter_6_table_1$Recall, chapter_6_table_1$Minutes, mean)
Mean_Error_Linear <- Actual_Means - Predicted_Linear
rbind(Actual_Means, Predicted_Linear, Mean_Error_Linear)HideShow
1 2 3 4
Actual_Means 2.0 6.0 8.0 9.0
Predicted_Linear 2.8 5.1 7.4 9.7
Mean_Error_Linear -0.8 0.9 0.6 -0.7If the only true trend in the data were linear, these errors would show no pattern. Instead they run , , , — below, above, above, below — which is the signature of a quadratic component, here in its concave-down (inverted-U) form, the shape of the book’s Figure 6.3(b).
Figure 6.4. Scatterplot with the linear trend removed
The same 24 scores as Figure 6.1, with the linear trend removed: each point is a participant’s residual from the linear model (actual recall minus the predicted value of 2.8, 5.1, 7.4, or 9.7 for that study time).
HideShow
ggplot(d6, aes(Minutes, resid_lin)) +
geom_hline(yintercept = 0, color = "#0C2340", linewidth = 0.6) +
geom_point(shape = 4, size = 2.6, stroke = 0.9) +
scale_x_continuous(breaks = 1:4) +
scale_y_continuous(limits = c(-6, 6), breaks = -6:6) +
labs(title = "Figure 6.4. Scatterplot of Figure 6.1 data with linear trend removed",
x = "Study time (minutes allotted)", y = "Recall with linear trend removed")Figure 6.4. Scatterplot of Figure 6.1 data with linear trend removed.
Figure 6.5. Sample means with the linear trend removed
The group-level version of Figure 6.4: the mean error for each study time, namely , , , and . These four points trace an inverted U — the concave-down quadratic curve of the book’s Figure 6.3(b) — the trend the linear model has not captured.
HideShow
mean_err_lin <- group_means |>
mutate(mean_error = Recall - pred_lin)
ggplot(mean_err_lin, aes(Minutes, mean_error)) +
geom_hline(yintercept = 0, color = "#0C2340", linewidth = 0.6) +
geom_point(shape = 0, size = 3.2, stroke = 1) +
scale_x_continuous(breaks = 1:4) +
scale_y_continuous(limits = c(-6, 6), breaks = -6:6) +
labs(title = "Figure 6.5. Sample means with linear trend removed",
x = "Study time (minutes allotted)", y = "Mean recall with linear trend removed")Figure 6.5. Plot of sample means with linear trend removed.
The quadratic trend model
Adding to the model (the
I() function protects the arithmetic inside the formula)
gives a model with both linear and quadratic trends.
HideShow
Call:
lm(formula = Recall ~ Minutes + I(Minutes^2), data = chapter_6_table_1)
Residuals:
Min 1Q Median 3Q Max
-3.150 -0.975 0.050 1.150 2.150
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -3.2500 1.8937 -1.716 0.10083
Minutes 6.0500 1.7275 3.502 0.00212 **
I(Minutes^2) -0.7500 0.3401 -2.205 0.03873 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 1.666 on 21 degrees of freedom
Multiple R-squared: 0.7471, Adjusted R-squared: 0.723
F-statistic: 31.01 on 2 and 21 DF, p-value: 5.389e-07HideShow
2.5 % 97.5 %
(Intercept) -7.188062 0.68806206
Minutes 2.457378 9.64262231
I(Minutes^2) -1.457297 -0.04270317The coefficients match Equation 6.24, . Its predicted means come much closer to the observed means.
HideShow
1 2 3 4
Actual_Means 2.00 6.00 8.00 9.00
Predicted_Quadratic 2.05 5.85 8.15 8.95The quadratic term raises the predictions for Groups 2 and 3 and lowers them for Groups 1 and 4 — exactly the correction Figure 6.5 called for.
Figure 6.6. Sample means and estimated means from the quadratic model
The four sample means (circles) with the means predicted by the quadratic model of Equation 6.24 (squares), 2.05, 5.85, 8.15, and 8.95, and the fitted curve through them. The estimated points now sit almost on top of the sample means, a much closer fit than the straight line of Figure 6.2.
HideShow
quad_curve <- data.frame(Minutes = seq(1, 4, length.out = 200))
quad_curve$Recall <- predict(quad_fit, newdata = quad_curve)
fig_6_6_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_quad,
Kind = "Predicted mean")
)
fig_6_6_points$Kind <- factor(fig_6_6_points$Kind,
levels = c("Sample mean", "Predicted mean"))
ggplot(fig_6_6_points, aes(Minutes, Value, shape = Kind, color = Kind)) +
geom_line(data = quad_curve, aes(Minutes, Recall),
inherit.aes = FALSE, color = "#0C2340", linewidth = 0.8) +
geom_point(size = 3.6, stroke = 1) +
scale_shape_manual(name = NULL, values = c("Sample mean" = 1, "Predicted mean" = 0)) +
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.6. Sample means and estimated means from the quadratic model",
x = "Study time (minutes allotted)", y = "Recall (number of words)") +
theme(legend.position = "top")Figure 6.6. Plot of sample means and estimated means from quadratic model.
The cubic trend model
The cubic trend was not significant, but it is instructive to see what adding it does.
HideShow
Call:
lm(formula = Recall ~ Minutes + I(Minutes^2) + I(Minutes^3),
data = chapter_6_table_1)
Residuals:
Min 1Q Median 3Q Max
-3 -1 0 1 2
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -5.0000 5.7749 -0.866 0.397
Minutes 8.8333 8.8320 1.000 0.329
I(Minutes^2) -2.0000 3.9019 -0.513 0.614
I(Minutes^3) 0.1667 0.5182 0.322 0.751
Residual standard error: 1.703 on 20 degrees of freedom
Multiple R-squared: 0.7484, Adjusted R-squared: 0.7106
F-statistic: 19.83 on 3 and 20 DF, p-value: 3.306e-06HideShow
2.5 % 97.5 %
(Intercept) -17.046326 7.046326
Minutes -9.589944 27.256610
I(Minutes^2) -10.139268 6.139268
I(Minutes^3) -0.914254 1.247587HideShow
1 2 3 4
Actual_Means 2 6 8 9
Predicted_Cubic 2 6 8 9The predicted means are literally identical to the observed sample means. With four groups, a model with three trend components explains all between-group variance; that is a mathematical necessity, not evidence that the cubic term is needed. Because the quadratic model already fit closely, there is no practical case for the cubic.
The two figures below make this point visually. With the linear and quadratic trends removed, almost nothing remains at either the individual or the group level.
Figure 6.7. Scatterplot with linear and quadratic trends removed
The 24 scores again, now with both the linear and the quadratic trends removed: each point is a participant’s residual from the quadratic model. The points scatter around zero with no clear remaining shape, the visual counterpart of the non-significant cubic trend.
HideShow
ggplot(d6, aes(Minutes, resid_quad)) +
geom_hline(yintercept = 0, color = "#0C2340", linewidth = 0.6) +
geom_point(shape = 4, size = 2.6, stroke = 0.9) +
scale_x_continuous(breaks = 1:4) +
scale_y_continuous(limits = c(-6, 6), breaks = -6:6) +
labs(title = "Figure 6.7. Scatterplot of Figure 6.1 data with linear and quadratic trends removed",
x = "Study time (minutes allotted)",
y = "Recall with linear and quadratic trends removed")Figure 6.7. Scatterplot of Figure 6.1 data with linear and quadratic trends removed.
Figure 6.8. Sample means with linear and quadratic trends removed
The group-level mean errors from the quadratic model, drawn on the same vertical scale as Figure 6.5 so the shrinkage is visible. All four hover within a fraction of a word of zero. The pattern that remains is necessarily a cubic one — it is the only shape that can survive once the linear and quadratic trends are gone — but it is far too small to matter, consistent with the non-significant cubic trend in Table 6.3.
HideShow
1 2 3 4
-0.05 0.15 -0.15 0.05 HideShow
#> -0.05, 0.15, -0.15, 0.05 — the values plotted in Figure 6.8 on book p. 290
ggplot(mean_err_quad, aes(Minutes, mean_error)) +
geom_hline(yintercept = 0, color = "#0C2340", linewidth = 0.6) +
geom_point(shape = 5, size = 3.2, stroke = 1) +
scale_x_continuous(breaks = 1:4) +
scale_y_continuous(limits = c(-6, 6), breaks = -6:6) +
labs(title = "Figure 6.8. Sample means with linear and quadratic trends removed",
x = "Study time (minutes allotted)",
y = "Mean recall with linear and quadratic trends removed")Figure 6.8. Plot of sample means with linear and quadratic trends removed.
Comparing the three polynomial models
The linear, quadratic, and cubic fits are nested: each adds one term
to the one before it. anova() gives the sequential model
comparison, each line testing whether the added term improves fit. The
quadratic term is a clear improvement over the linear-only model; the
cubic term is not.
HideShow
Analysis of Variance Table
Model 1: Recall ~ Minutes
Model 2: Recall ~ Minutes + I(Minutes^2)
Model 3: Recall ~ Minutes + I(Minutes^2) + I(Minutes^3)
Res.Df RSS Df Sum of Sq F Pr(>F)
1 22 71.8
2 21 58.3 1 13.5 4.6552 0.0433 *
3 20 58.0 1 0.3 0.1034 0.7511
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1A side-by-side table makes the three models easy to compare. With modelsummary, each model is in its own column with standard errors in parentheses and fit statistics at the foot.
HideShow
modelsummary(
list("Linear" = Regression_Object,
"Quadratic" = Regression_Object2,
"Cubic" = Regression_Object3),
estimate = "{estimate}",
statistic = "({std.error})", # standard errors in parentheses, APA style
gof_map = c("nobs", "aic", "bic", "logLik"),
stars = TRUE,
output = "gt" # gt backend, to match the gtsummary table below
)| Linear | Quadratic | Cubic | |
|---|---|---|---|
| (Intercept) | 0.500 | -3.250 | -5.000 |
| (0.903) | (1.894) | (5.775) | |
| Minutes | 2.300 | 6.050 | 8.833 |
| (0.330) | (1.728) | (8.832) | |
| I(Minutes^2) | -0.750 | -2.000 | |
| (0.340) | (3.902) | ||
| I(Minutes^3) | 0.167 | ||
| (0.518) | |||
| Num.Obs. | 24 | 24 | 24 |
| AIC | 100.4 | 97.4 | 99.3 |
| BIC | 103.9 | 102.1 | 105.2 |
| Log.Lik. | -47.204 | -44.705 | -44.643 |
| + p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001 | |||
The same comparison as a gtsummary table, each model under its own spanning header. The coefficient rows make the changing role of the linear term visible: its estimate shifts from 2.30 to 6.05 to 8.83 as higher-order terms are added, which is why the slope of a linear-only model and the coefficient of a polynomial model are not the same quantity.
HideShow
t_lin <- tbl_regression(Regression_Object, intercept = TRUE)
t_quad <- tbl_regression(Regression_Object2, intercept = TRUE)
t_cub <- tbl_regression(Regression_Object3, intercept = TRUE)
tbl_merge(list(t_lin, t_quad, t_cub),
tab_spanner = c("**Linear**", "**Quadratic**", "**Cubic**"),
quiet = TRUE) # the models have different numbers of terms; row order is fine| Characteristic |
Linear
|
Quadratic
|
Cubic
|
||||||
|---|---|---|---|---|---|---|---|---|---|
| Beta | 95% CI | p-value | Beta | 95% CI | p-value | Beta | 95% CI | p-value | |
| (Intercept) | 0.50 | -1.4, 2.4 | 0.6 | -3.3 | -7.2, 0.69 | 0.10 | -5.0 | -17, 7.0 | 0.4 |
| Minutes | 2.3 | 1.6, 3.0 | <0.001 | 6.1 | 2.5, 9.6 | 0.002 | 8.8 | -9.6, 27 | 0.3 |
| I(Minutes^2) | -0.75 | -1.5, -0.04 | 0.039 | -2.0 | -10, 6.1 | 0.6 | |||
| I(Minutes^3) | 0.17 | -0.91, 1.2 | 0.8 | ||||||
| Abbreviation: CI = Confidence Interval | |||||||||
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
Arel-Bundock V (2026). modelsummary: Summary Tables and Plots for Statistical Models and Data: Beautiful, Customizable, and Publication-Ready. doi:10.32614/CRAN.package.modelsummary https://doi.org/10.32614/CRAN.package.modelsummary. R package version 2.6.0, https://CRAN.R-project.org/package=modelsummary.
Iannone R, Cheng J, Schloerke B, Haughton S, Hughes E, Lauer A, François R, Seo J, Brevoort K, Roy O (2026). gt: Easily Create Presentation-Ready Display Tables. doi:10.32614/CRAN.package.gt https://doi.org/10.32614/CRAN.package.gt. R package version 1.3.0, https://CRAN.R-project.org/package=gt.
Kelley K (2026). DMAR: Design, Measurement, and Analysis in R (DMAR). R package version 1.2.0, https://kenkelley.org.
Maxwell S, Delaney H, Kelley K (2026). AMCP: Data Sets to Accompany Designing Experiments and Analyzing Data: A Model Comparison Perspective (Maxwell, Delaney, and Kelley, 2027, 4th Edition). doi:10.32614/CRAN.package.AMCP https://doi.org/10.32614/CRAN.package.AMCP. R package version 2.0.0, https://CRAN.R-project.org/package=AMCP.
Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. doi:10.32614/R.manuals https://doi.org/10.32614/R.manuals. https://www.R-project.org/.
Sjoberg D, Larmarange J, Curry M, de la Rua E, Lavery J, Whiting K, Zabor E (2026). gtsummary: Presentation-Ready Data Summary and Analytic Result Tables. doi:10.32614/CRAN.package.gtsummary https://doi.org/10.32614/CRAN.package.gtsummary. R package version 2.5.1, https://CRAN.R-project.org/package=gtsummary.
Wickham H, Chang W, Henry L, Pedersen T, Takahashi K, Wilke C, Woo K, Yutani H, Dunnington D, van den Brand T (2026). ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics. doi:10.32614/CRAN.package.ggplot2 https://doi.org/10.32614/CRAN.package.ggplot2. R package version 4.0.3, https://CRAN.R-project.org/package=ggplot2.
Wickham H, François R, Henry L, Müller K, Vaughan D (2026). dplyr: A Grammar of Data Manipulation. doi:10.32614/CRAN.package.dplyr https://doi.org/10.32614/CRAN.package.dplyr. R package version 1.2.1, https://CRAN.R-project.org/package=dplyr.