Examples follow the book’s section numbers.
Chapter 1 is largely conceptual, situating statistical reasoning within the philosophy and history of science. The quantitative material appears in Section 1.4, Introduction to the Fisher Tradition, which develops two classic examples from first principles: a discrete probability example (Fisher’s tea-tasting experiment, §1.4.2) and a randomization test (the Bayley twins example, §1.4.3). This document reproduces those examples in R, one-to-one with the book.
# Load all of the packages used.
library(AMCP) # the textbook's data sets
library(DMAR) # design, measurement, and analysis
library(ggplot2) # the grammar of graphics used for the book's data figures
library(dplyr) # data manipulation used by some of the figuresR ignores everything to the right of a # on a line, so
the comments in the code throughout this page are notes to the reader
rather than instructions to R.
The AMCP package supplies the book’s data. Install the packages used in this chapter from CRAN once.
With AMCP loaded, data() brings a data set into the
session. The names follow the book’s own numbering:
chapter_1_table_1 holds Table 1.1 and
chapter_11_table_20 holds Table 11.20, while the data
behind an end-of-chapter exercise replace table with
exercise, as in chapter_1_exercise_21. Short forms
work as well, abbreviating those two as C1T1 and
C1E21. A suffix marks the few data sets that come in more
than one form: _raw where the book itself prints only
summary statistics (chapter_3_table_7_raw), and
_univariate where the same data are also supplied in a long
layout (chapter_15_exercise_18_univariate).
data(package = "AMCP") lists every data set in the package,
and ?chapter_1_table_1 documents an individual one.
The data set we use here is chapter_1_table_1, the Bayley Mental Scale scores for ten pairs of twins shown in Table 1.1 of the book. We return to these data for the randomization test in §1.4.3; for now they give us a concrete data set on which to introduce some base R.
We load a data set with the data() function.
To see the data, simply type its name. Output on these pages is shown
directly beneath the code that produced it, without a prefix; in your
own console R prefixes printed values with an index such as
[1]. (Pressing the up arrow in the console recalls a
previously entered command, ready to run again.)
treat control week
1 28 32 1
2 31 25 1
3 25 15 1
4 23 25 1
5 28 16 1
6 26 30 2
7 36 24 2
8 23 13 2
9 23 25 2
10 24 16 2
The data are organized by condition (treat,
control) and by week, with one row per twin
pair. For larger data sets you may want only the first part (with
head()) or the last part (with tail()).
treat control week
1 28 32 1
2 31 25 1
3 25 15 1
4 23 25 1
5 28 16 1
6 26 30 2
treat control week
5 28 16 1
6 26 30 2
7 36 24 2
8 23 13 2
9 23 25 2
10 24 16 2
This is a paired (matched-pairs) design, so a natural quantity is the
difference between the two paired conditions. We extract the
treat and control values, subtract, and store
the result as a new variable, Difference, in the data
frame.
The $ operator extracts the variable on its right from
the data frame on its left; for example, Data$Score
extracts Score from Data. Placing
$ after a data frame and a new name, together with
the assignment operator <-, creates that new variable in
the data frame. The assignment operator assigns what is on the right
(here, the result of a calculation) to the object on the left.
chapter_1_table_1$Difference <- chapter_1_table_1$treat - chapter_1_table_1$control
chapter_1_table_1 treat control week Difference
1 28 32 1 -4
2 31 25 1 6
3 25 15 1 10
4 23 25 1 -2
5 28 16 1 12
6 26 30 2 -4
7 36 24 2 12
8 23 13 2 10
9 23 25 2 -2
10 24 16 2 8
There are many ways to summarize data in R. Using only base R (the functions that come with R, with no add-on packages), we can extract a subset of interest and then apply a function to it. Subsetting matters here because the data are structured by condition and by week, and because—this being a paired design—there is a linkage among the scores that we should respect.
We subset with square brackets, Data[rows, columns]. To
the left of the comma we identify the rows:
chapter_1_table_1$week == 1 returns
TRUE/FALSE for each row, and R keeps the
TRUE rows. To the right of the comma we name the column.
For example, the Week 1 scores for the Treatment group are:
[1] 28 31 25 23 28
Applying a few functions to that subset gives descriptive statistics for the Week 1 Treatment group (other descriptive statistics can be requested as well):
[1] 135
[1] 27
[1] 3.082207
Min. 1st Qu. Median Mean 3rd Qu. Max.
23 25 28 27 28 31
The same pattern gives the Week 1 Control group:
[1] 113
[1] 22.6
[1] 7.092249
Min. 1st Qu. Median Mean 3rd Qu. Max.
15.0 16.0 25.0 22.6 25.0 32.0
Rather than repeating this subsetting for every week-by-condition
combination, we can reproduce the weekly sums of Table 1.1 at once,
along with the corresponding weekly means (which the table itself does
not report). The aggregate() function applies a function to
each variable, broken down by week:
# Weekly sums
aggregate(cbind(treat, control, Difference) ~ week, data = chapter_1_table_1, FUN = sum) week treat control Difference
1 1 135 113 22
2 2 132 108 24
#> 135 / 113 / 22 (Week 1) and 132 / 108 / 24 (Week 2) — matches book p. 29, Table 1.1
# Weekly means
aggregate(cbind(treat, control, Difference) ~ week, data = chapter_1_table_1, FUN = mean) week treat control Difference
1 1 27.0 22.6 4.4
2 2 26.4 21.6 4.8
The overall (two-week) sums and means, the last two rows of Table
1.1, follow from colSums() and colMeans():
treat control Difference
267 221 46
treat control Difference
26.7 22.1 4.6
Section 1.4 of the book derives two statistical tests entirely from first principles, so that the meaning of a value is transparent rather than something “looked up in a table.” Section 1.4.1 is conceptual; the worked examples begin in §1.4.2.
This is Fisher’s famous tea-tasting experiment. A lady claims she can taste whether the milk or the tea was poured first. She is given eight cups—four milk-first (MF) and four tea-first (TF), in random order—and asked to sort them into the two groups of four. If she cannot discriminate at all, every way of choosing four cups to call “milk-first” is equally likely, so the probability of a perfect performance by chance is one divided by the number of such choices.
How many ways are there to choose four cups out of eight to label MF? Following the book’s reasoning, there are ways to choose four cups in a particular order:
[1] 1680
But order does not matter—(A, B, C, D) is the same set as (D, C, B, A)—and each distinct set of four can be ordered in ways:
[1] 24
Dividing the ordered count by the number of orderings of each set gives the number of distinct sets of four cups. This is Equation (1.2) in the book:
[1] 70
This quantity is the number of combinations of eight things taken
four at a time, . R
computes combinations directly with choose(n, k):
[1] 70
The general counting rule, , is Equation (1.3). The
factorial() function evaluates it and returns the same 70
(note that factorial() can overflow for large arguments,
which is one reason choose() is preferred in practice):
[1] 70
Because only one of these 70 equally likely divisions is exactly correct, the probability of a perfect classification by chance alone is . This is Equation (1.1):
[1] 0.01428571
That value, about .014, is below the conventional .05 criterion: a perfect performance would be convincing evidence of discrimination ability.
To actually enumerate the choices, combn()
returns a matrix whose columns are the distinct sets. There are 70
columns (one per set), so we look at the dimensions and the first few
columns rather than printing all of them:
[1] 4 70
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 1 1 1 1 1 1 1
[2,] 2 2 2 2 2 2 2 2
[3,] 3 3 3 3 3 4 4 4
[4,] 4 5 6 7 8 5 6 7
Combinations are unordered choices. Permutations are ordered choices and count (A, B) and (B, A) separately. The number of ordered selections of four cups from eight—the 1,680 from earlier—is the permutation :
[1] 1680
Base R has no function to enumerate permutations directly;
see the permutations() function in the gtools package if a
listing is needed.
Now consider a near-perfect performance: three of the four MF cups classified correctly. Misclassifying one MF cup necessarily means one TF cup was also misclassified, and the two choices are made independently. The number of ways to make one error of each kind is , Equation (1.4):
[1] 16
The probability of that near-perfect outcome is this count over the 70 possible divisions, Equation (1.5):
# Equation (1.5): probability of three MF (and one TF) classified as MF
choose(n = 4, k = 3) * choose(n = 4, k = 1) / choose(n = 8, k = 4)[1] 0.2285714
So the probability of performance at least this good—three or four correct—is the sum of the two cases, :
[1] 0.2428571
Because .243 far exceeds .05, even the next-best-to-perfect outcome
would not be convincing. Every probability computed above is a special
case of the general rule in Equation (1.6) for selecting items from , of which are “right.” That rule is the
hypergeometric probability, which R provides as
dhyper(). Here
cups, are truly MF
(m), are TF
(n), and the lady selects :
# Equation (1.6) via dhyper(): x correct of the 4 MF cups among the 4 labeled MF
dhyper(x = 3, m = 4, n = 4, k = 4) # three correct: 16/70 = .229[1] 0.2285714
[1] 0.01428571
[1] 0.2428571
The test we have just built by hand is, in general, the
Fisher-Irwin exact test, more commonly called
Fisher’s exact test. R implements it with
fisher.test(). The data are entered as a 2 × 2 table whose
rows are the lady’s guesses and whose columns are the actual
classifications.
We first consider a perfect performance (all four of each
kind correct). Using matrix() to enter the table:
TeaTasting_Perfect <- matrix(
c(4, 0, 0, 4),
nrow = 2,
dimnames = list(Guess = c("Milk-first", "Tea-first"),
Actual = c("Milk-first", "Tea-first"))
)
TeaTasting_Perfect Actual
Guess Milk-first Tea-first
Milk-first 4 0
Tea-first 0 4
Fisher's Exact Test for Count Data
data: TeaTasting_Perfect
p-value = 0.01429
alternative hypothesis: true odds ratio is greater than 1
95 percent confidence interval:
2.003768 Inf
sample estimates:
odds ratio
Inf
The one-sided value is 0.0143—exactly the we derived as Equation (1.1).
Now the near-perfect performance, with one error of each
kind. An alternative way to enter the table is with
rbind():
[,1] [,2]
Milk-first 3 1
Tea-first 1 3
Fisher's Exact Test for Count Data
data: TeaTasting_Near
p-value = 0.2429
alternative hypothesis: true odds ratio is greater than 1
95 percent confidence interval:
0.3135693 Inf
sample estimates:
odds ratio
6.408309
The one-sided value is
0.2429—exactly the we obtained for “three or four correct.” So
fisher.test() simply automates the counting we did by hand.
(The reported odds-ratio estimate is a conditional maximum likelihood
estimate and differs from the simple sample odds ratio; see
?fisher.test.)
Beyond the value, it is useful to describe the magnitude of the effect. One option for a 2 × 2 table is the phi coefficient, which is the Pearson correlation between two binary variables—here, each cup’s Actual category and the lady’s Judged category. In the one-error-of-each-kind case the eight cups give the pairs the book lists, and the correlation is .50:
Actual <- c(1, 1, 1, 1, 2, 2, 2, 2) # true category of each cup (four MF, four TF)
Judged <- c(1, 1, 1, 2, 1, 2, 2, 2) # the lady's classification (one error of each kind)
cor(Actual, Judged)[1] 0.5
A phi of .50 corresponds to a large effect by Cohen’s benchmarks (.10, .30, .50 for small, medium, large).
A second option is the odds ratio, Equation (1.7), the ratio of the odds of “success” in the two rows:
A small function makes this reusable. For the hypothesized success probabilities used in the power calculation below (, ), the odds ratio is 21:
[1] 21
This subsection follows the book’s footnote on the power of Fisher’s exact test and may be skipped on a first reading.
Power is the probability of detecting a true effect. For Fisher’s exact test with fixed marginals, power is computed from the noncentral hypergeometric distribution, whose noncentrality is the odds ratio of the true success probabilities in the two rows. Suppose a tea-first cup is truly classified “tea-first” with probability .9 and a milk-first cup with probability .3, giving :
p1 <- 0.9 # P(classify a tea-first cup as "tea-first")
p2 <- 0.3 # P(classify a milk-first cup as "tea-first")
theta <- odds_ratio(p1, p2)
theta[1] 21
With four cups of each kind, the only convincing outcome is perfect classification (all four, ). Summing the noncentral hypergeometric probabilities over the rejection region gives the power:
numerator <- choose(4, 4) * choose(4, 0) * theta^4
denominator <- sum(sapply(0:4, function(i) choose(4, i) * choose(4, 4 - i) * theta^i))
numerator / denominator[1] 0.541926
The power is about .542. This is appreciably larger than the value obtained if one incorrectly treats the two rows as independent binomials (as some software does), which assumes the lady is not constrained to give four responses of each kind:
[1] 0.1575296
That value, about .158, differs markedly from the correct .542—a reminder that the appropriate power computation depends on how the experiment constrains the responses.
The DMAR
package automates the power calculation with
power_fisher_exact(). It evaluates power under the
unconditional (independent-binomials) model, so it reports the
.158 value, not the conditional .542. It is the right tool when the two
margins are free to vary rather than fixed at four responses of each
kind.
power_fisher_exact(n_1 = 4, n_2 = 4, p_1 = 0.9, p_2 = 0.3,
alpha = 1 / choose(8, 4), alternative = "greater")| term | value |
|---|---|
| power | 0.158 |
| odds_ratio_alt | 21 |
| p_1 | 0.900 |
| p_2 | 0.300 |
| expected_s | 4.800 |
| n_1 | 4 |
| n_2 | 4 |
| alpha_level | 0.014 |
The power row reproduces the .158 independent-binomials
value computed by hand just above; the agreement confirms that the two
routes are the same calculation. What the call buys over the one-line
hand formula is that it takes the two cell probabilities directly and
reports the implied odds ratio and expected number of successes
alongside the power, so the assumptions of the planned design are
visible in the output. The conditional .542 is the power given
the fixed margins of the tea-tasting design; the two answer different
questions, so a power analysis should be explicit about which model the
design implies.
The second example uses a quantitative outcome and again requires no
assumption about the shape of the population distribution. A
developmental psychologist asks whether brief training improves
2-year-olds’ scores on the Bayley Mental Scale. Ten pairs of twins take
part; one twin from each pair is randomly assigned to training, the
other to control. The measure of effect for each pair is the difference,
Treatment − Control—the Difference variable we
created earlier from chapter_1_table_1 (Table 1.1). The
observed differences sum to 46.
Under the null hypothesis, the treatment has no effect, so each pair’s two scores were predetermined and the random assignment merely decided which sign the difference carried. With 10 pairs, there are equally likely sign patterns; with the 5 pairs from Week 1 alone, there are :
[1] 32
[1] 1024
If the first week were the whole experiment, we would have five differences, hence possible assignments of signs. The observed Week 1 differences are:
[1] -4 6 10 -2 12
expand.grid() lists every combination of the supplied
values. Giving it each observed difference paired with its sign-reversed
value produces all 32 sign patterns (this reproduces Table 1.2 of the
book; the first listed value of each pair is the observed
difference):
Possible_Assignments_Week1 <- expand.grid(
Pair1 = c(-4, 4),
Pair2 = c( 6, -6),
Pair3 = c(10, -10),
Pair4 = c(-2, 2),
Pair5 = c(12, -12)
)
head(Possible_Assignments_Week1) Pair1 Pair2 Pair3 Pair4 Pair5
1 -4 6 10 -2 12
2 4 6 10 -2 12
3 -4 -6 10 -2 12
4 4 -6 10 -2 12
5 -4 6 -10 -2 12
6 4 6 -10 -2 12
We sum each row with apply() (using
MARGIN = 1 to work row by row), then ask what proportion of
the 32 sums are at least as large as the observed Week 1 total of 22.
Because every sign pattern is equally likely under the null hypothesis,
that proportion is the one-tailed
value:
[1] 34 30 26 22 22 18 14 14 10 10 10 6 6 2 2 2 -2 -2 -2
[20] -6 -6 -10 -10 -10 -14 -14 -18 -22 -22 -26 -30 -34
[1] 5
[1] 0.15625
Five of the 32 assignments give a total of 22 or more, so the one-tailed probability is —not small enough to claim significance for Week 1 alone.
Section 1.4.3 develops a randomization test from the five
matched-pairs difference scores observed in Week 1. Under the null
hypothesis that training had no effect, each pair’s difference was
equally likely to carry a plus or a minus sign, giving equally likely totals. This
figure is the grouped relative-frequency histogram of those 32 totals,
with the bars at totals at least as large as the observed +22 shaded;
that shaded area, ,
is the one-tailed value. We build
the 32 totals directly from chapter_1_table_1, so the
figure is reproduced exactly rather than transcribed.
# week1_diff was created above from Table 1.1; its total is the observed +22.
observed_total <- sum(week1_diff)
# All 2^5 = 32 sign patterns; each row's total is one possible reassignment.
signs <- as.matrix(expand.grid(rep(list(c(1, -1)), length(week1_diff))))
totals <- as.vector(signs %*% week1_diff)
# Group the 32 totals into the book's width-8 bins. Each bin spans two of the
# possible totals (which are 4 apart), e.g. "-34 or -30", ..., "+30 or +34".
breaks <- seq(-36, 36, by = 8)
centers <- head(breaks, -1) + 4 # bin midpoints: -32, -24, ...
labels <- sprintf("%+d or %+d", centers - 2, centers + 2)
binned <- cut(totals, breaks = breaks, right = FALSE)
fig_1_2 <- data.frame(table(binned)) |>
mutate(center = centers,
label = factor(labels, levels = labels),
# Shade the bins whose totals are >= the observed +22.
shaded = center + 2 >= observed_total)
ggplot(fig_1_2, aes(label, Freq / 32, fill = shaded)) +
geom_col(color = "black", width = 1) +
scale_fill_manual(values = c(`FALSE` = "white",
`TRUE` = "#0C2340"),
guide = "none") +
# Break on whole counts out of 32 so the axis reads 0/32, 1/32, 2/32, ...
scale_y_continuous(breaks = (0:8) / 32,
labels = function(p) paste0(round(p * 32), "/32")) +
labs(x = "Total of difference scores", y = "Relative frequency") +
theme(axis.text.x = element_text(size = rel(0.85)))Figure 1.2. Distribution of possible totals of difference scores using data from Week 1.
The two shaded bars are the totals of +22 or more (the +22-or-+26 bin and the +30-or-+34 bin); together they hold 5 of the 32 equally likely totals, the that Section 1.4.3 reports for Week 1 alone.
Listing all
sign patterns by hand is impractical, so we write a small function that
builds them for any set of differences. expand.grid()
produces every combination of
and across the pairs;
multiplying those sign patterns by the differences and summing gives one
total per assignment:
all_signflip_sums <- function(differences) {
n <- length(differences)
# Each row of 'signs' is one of the 2^n ways to attach +1 or -1 to each difference.
signs <- as.matrix(expand.grid(rep(list(c(1, -1)), n)))
# Multiply each sign pattern by the differences and sum: one total per assignment.
as.vector(signs %*% differences)
}The function reproduces the Week 1 result, and then gives us the full ten-pair distribution:
[1] 0.15625
# All ten pairs
all_diff <- chapter_1_table_1$Difference
all_sums <- all_signflip_sums(all_diff)
observed_sum <- sum(all_diff)
observed_sum # 46[1] 46
[1] 1024
The one-tailed value is the proportion of the 1,024 totals that are at least 46:
[1] 40
[1] 0.0390625
Only 40 of 1,024 assignments (about .039) reach the observed total, so a one-tailed randomization test gives significant evidence that training improved performance. The breakdown by how the totals compare to 46 reproduces Table 1.3:
c(greater = sum(all_sums > observed_sum),
equal = sum(all_sums == observed_sum),
less = sum(all_sums < observed_sum)) # 26, 14, 984greater equal less
26 14 984
Because the randomization distribution is symmetric, a two-tailed test counts totals at least as extreme as 46 in either direction, giving :
[1] 80
[1] 0.078125
So the directional conclusion (one-tailed .039) and the nondirectional conclusion (two-tailed .078) differ on the .05 criterion—a reminder that the choice of a one- or two-tailed test must be made on substantive grounds.
The hand enumeration above is exactly what DMAR’s
randomization_test_paired() automates. It enumerates all
sign patterns when is small (here , so all 1,024) and falls back to
Monte Carlo sampling when is
large. The x = control, y = treat ordering matches the
book’s Treatment − Control direction:
randomization_test_paired(x = chapter_1_table_1$control,
y = chapter_1_table_1$treat,
statistic = "mean", alternative = "greater")| term | value |
|---|---|
| statistic | 4.600 |
| p_value | 0.0391 |
| n_pairs | 10 |
| n_evaluated | 1024 |
| exact | 1 |
The p_value row reproduces the one-tailed ; the two-sided
version (set alternative = "two.sided") returns the we found by hand.
The hand enumeration and the DMAR call agree exactly, as they must—the
function automates the counting rather than substituting a different
test. What it buys is the bookkeeping and a Monte Carlo fallback for a
sample too large to enumerate, neither of which changes the answer
here.
The value says how surprising the result is under the null hypothesis; it does not say how large the effect is. For a matched-pairs design a natural companion is the probability of superiority: the probability that the trained twin of a pair outscores its control. It uses only the order within each pair, not the size of the difference, so no distributional assumption is needed—the same spirit as the randomization test.
Base R gets the estimate by counting, with no package at all. Each pair is one comparison, so we count the pairs training won, the pairs that tied, and take the proportion:
[1] 6
[1] 0
[1] 0.6
Six of the ten pairs favor training, so the estimate is . Because the sampling unit is
the pair and no pair is tied, that proportion is a binomial one, and
base R’s binom.test() attaches an exact (Clopper–Pearson)
interval to it:
binom.test(
x = sum(chapter_1_table_1$treat > chapter_1_table_1$control),
n = nrow(chapter_1_table_1),
p = 0.5,
alternative = "two.sided",
conf.level = 0.95
)
Exact binomial test
data: sum(chapter_1_table_1$treat > chapter_1_table_1$control) and nrow(chapter_1_table_1)
number of successes = 6, number of trials = 10, p-value = 0.7539
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
0.2623781 0.8784477
sample estimates:
probability of success
0.6
The estimate is .60 with a 95% interval of about .262 to .878—wide,
as it must be with only ten pairs. The value binom.test() reports
here is the sign test, and it is a useful contrast
rather than a competitor: keeping only the signs and discarding the
magnitudes throws away the information the randomization test used,
which is why its value (about
.75) is so much larger than the .039 above.
DMAR’s probability_of_superiority_paired() reports the
same quantity directly:
probability_of_superiority_paired(x = chapter_1_table_1$control,
y = chapter_1_table_1$treat,
conf_level = 0.95)| term | value |
|---|---|
| probability_of_superiority | 0.600 |
| ci_lower | 0.297 |
| ci_upper | 0.842 |
| var_ps | 0.024 |
| wins_y_over_x | 6 |
| losses_y_under_x | 4 |
| ties | 0 |
Confidence level: 95%
The probability_of_superiority row is .600, agreeing
exactly with the mean() count above—the agreement is the
check that the two routes are computing the same thing. What the DMAR
call adds is what the counting route leaves the reader to assemble by
hand: the win/loss/tie breakdown (wins_y_over_x,
losses_y_under_x, ties) and the variance of
the estimate reported alongside the estimate, ties credited as half a
win rather than silently dropped by a bare > comparison,
and an interval—.297 to .842 here—built for this estimand on a
transformed scale so that it cannot run outside 0 and 1. It is a
large-sample interval and so differs from the exact binomial interval
above; with ten pairs the two bracket .60 similarly and neither is
narrow.
The book notes that a paired -test, although it makes more
assumptions, is a close approximation to the randomization test. R’s
t.test() performs a one-sample, paired, or
independent-samples -test
depending on its arguments. A one-sample test on the 10 difference
scores is equivalent to a paired test (the default null value is 0,
changeable with mu =):
One Sample t-test
data: chapter_1_table_1$Difference
t = 2.1386, df = 9, p-value = 0.06116
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
-0.2658294 9.4658294
sample estimates:
mean of x
4.6
Equivalently, supply the two conditions and declare the design paired:
Paired t-test
data: chapter_1_table_1$treat and chapter_1_table_1$control
t = 2.1386, df = 9, p-value = 0.06116
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
-0.2658294 9.4658294
sample estimates:
mean difference
4.6
This gives on 9 degrees of freedom, with a two-tailed value of about .061. The book reports the matching one-tailed value, .031, which we obtain with the directional alternative:
Paired t-test
data: chapter_1_table_1$treat and chapter_1_table_1$control
t = 2.1386, df = 9, p-value = 0.03058
alternative hypothesis: true mean difference is greater than 0
95 percent confidence interval:
0.6570313 Inf
sample estimates:
mean difference
4.6
The one-tailed -test value, .031, is close to the .039 from the exact randomization test—the correspondence the book emphasizes. The book notes that the agreement is closer still once the test is corrected for the discontinuous nature of these data, at which point the two probabilities differ by about 1 in 1,000, and the two tests may be viewed as very close approximations to one another. Deciding to reject the null hypothesis of the randomization test is tantamount to rejecting the null hypothesis of the -test.
Having derived the two tests above from first principles, the chapter turns to two classic data sets to make a foundational point concrete: although any single observation can be erratic, composite behavioral measurements tend to pile up in a roughly bell-shaped, approximately normal distribution. This near-normality is part of what motivates the normal-theory linear models developed throughout the book. The grouped frequencies behind the next two figures are read from the published figures and entered inline, since these historical raw data are not in the AMCP package.
Reaction time is a workhorse measure in experimental psychology. Although a single person’s reaction times over repeated trials are positively skewed, the distribution of average reaction times across people is very nearly normal. This figure shows that for the mean reaction times to sound of 1,000 Parisian machinist applicants (Fessard, 1926, as cited by Woodworth & Schlosberg, 1954), each measured over 30 trials, with a normal curve overlaid. Fessard excluded 35 extreme cases, leaving 965 (book p. 39). These historical raw data are not in the AMCP package, so the grouped frequencies below are read off the published figure’s bar heights and entered inline; they sum to 958 rather than 965, which is the accuracy of reading a printed histogram rather than a discrepancy with the book.
# Grouped frequencies read from Figure 1.3 (Fessard, 1926). Bars are centered at
# 130, 140, ..., 210 ms (bin width 10 ms); 35 of the original 1,000 cases were
# excluded by Fessard as extreme.
rt <- data.frame(
midpoint = seq(130, 210, by = 10),
frequency = c(27, 60, 125, 177, 202, 181, 105, 55, 26)
)
# A normal curve with the same total area as the histogram (n * bin width),
# using the mean and SD implied by the grouped data.
n_rt <- sum(rt$frequency)
bin_rt <- 10
mean_rt <- with(rt, sum(midpoint * frequency) / n_rt)
sd_rt <- with(rt, sqrt(sum(frequency * (midpoint - mean_rt)^2) / (n_rt - 1)))
curve_rt <- data.frame(x = seq(115, 225, length.out = 400))
curve_rt$y <- dnorm(curve_rt$x, mean_rt, sd_rt) * n_rt * bin_rt
ggplot(rt, aes(midpoint, frequency)) +
geom_col(width = bin_rt, fill = "grey35",
color = "white", alpha = 0.9) +
geom_line(data = curve_rt, aes(x, y),
color = "#0C2340", linewidth = 1) +
scale_x_continuous(breaks = seq(130, 210, by = 10)) +
labs(x = "Reaction time (in milliseconds)", y = "Frequency")Figure 1.3. Grouped frequency distribution of simple reaction times.
The average reaction times pile up symmetrically around roughly 170 ms and track the overlaid normal curve closely, the chapter’s first empirical illustration of approximate normality in a behavioral measure (book p. 39).
A second illustration of approximate normality comes from a personality scale. This figure shows the distribution of Hypochondriasis-scale scores for 699 Minnesotans who were not ill but accompanied relatives or friends to a hospital (McKinley & Hathaway, 1956, originally described in Hathaway & McKinley, 1940), again with a normal curve overlaid (book pp. 39–40). As with the reaction-time data, the composite nature of the score (a sum over many items) produces a roughly bell-shaped distribution. As for Figure 1.3, the frequencies below are read off the published figure’s bar heights and entered inline; they sum to 698 rather than the 699 the book reports.
# Grouped frequencies read from Figure 1.4 (McKinley & Hathaway, 1956). Bars span
# T scores from about 20 to 80 in steps of 3.
mmpi <- data.frame(
Tscore = seq(20, 80, by = 3),
frequency = c(1, 5, 5, 9, 20, 24, 46, 76, 65, 95, 98,
63, 52, 50, 37, 18, 19, 7, 5, 2, 1)
)
# Normal curve scaled to the histogram's total area (n * bin width).
n_mm <- sum(mmpi$frequency)
bin_mm <- 3
mean_mm <- with(mmpi, sum(Tscore * frequency) / n_mm)
sd_mm <- with(mmpi, sqrt(sum(frequency * (Tscore - mean_mm)^2) / (n_mm - 1)))
curve_mm <- data.frame(x = seq(17, 83, length.out = 400))
curve_mm$y <- dnorm(curve_mm$x, mean_mm, sd_mm) * n_mm * bin_mm
ggplot(mmpi, aes(Tscore, frequency)) +
geom_col(width = bin_mm, fill = "grey35",
color = "white", alpha = 0.9) +
geom_line(data = curve_mm, aes(x, y),
color = "#0C2340", linewidth = 1) +
scale_x_continuous(breaks = seq(20, 80, by = 6)) +
labs(x = expression("MMPI hypochondriasis" ~ italic(T) ~ "score"), y = "Frequency")Figure 1.4. MMPI hypochondriasis scores.
The roughly 700 “Minnesota normals” produce a distribution centered near a score of 50 that, allowing for sampling variability, corresponds closely to the overlaid normal curve, reinforcing the chapter’s point that composite behavioral measurements are often approximately normal (book p. 40).
This chapter’s quantitative material builds two tests from first principles so that the value is something we derive, not merely look up:
choose(), factorial(),
combn(), and the hypergeometric dhyper()—and
automated by fisher.test(), together with the
phi-coefficient and odds-ratio effect sizes and the (advanced) power
computation.t.test().These ideas—deriving a reference distribution from the design itself, and the close agreement between randomization and normal-theory tests—motivate the normal-theory linear models developed in the chapters that follow.
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 1: The Logic of Experimental Design and 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.
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/.
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.