Chapter 1: The Logic of Experimental Design and 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 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.

HideShow
# 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 figures

R 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 book’s data in R

The AMCP package supplies the book’s data. Install the packages used in this chapter from CRAN once.

HideShow
install.packages(c("AMCP", "DMAR", "ggplot2", "dplyr"))

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.

R preliminaries with the Table 1.1 data

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.

Loading and viewing the data

We load a data set with the data() function.

HideShow
data(chapter_1_table_1)

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.)

HideShow
chapter_1_table_1
HideShow
   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()).

HideShow
head(chapter_1_table_1)
HideShow
  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
HideShow
tail(chapter_1_table_1)
HideShow
   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

Creating the difference score

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.

HideShow
chapter_1_table_1$Difference <- chapter_1_table_1$treat - chapter_1_table_1$control
chapter_1_table_1
HideShow
   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

Summarizing the data

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:

HideShow
chapter_1_table_1[chapter_1_table_1$week == 1, "treat"]
HideShow
[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):

HideShow
sum(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
[1] 135
HideShow
mean(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
[1] 27
HideShow
sd(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
[1] 3.082207
HideShow
summary(chapter_1_table_1[chapter_1_table_1$week == 1, "treat"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
     23      25      28      27      28      31 

The same pattern gives the Week 1 Control group:

HideShow
sum(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
[1] 113
HideShow
mean(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
[1] 22.6
HideShow
sd(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
[1] 7.092249
HideShow
summary(chapter_1_table_1[chapter_1_table_1$week == 1, "control"])
HideShow
   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:

HideShow
# Weekly sums
aggregate(cbind(treat, control, Difference) ~ week, data = chapter_1_table_1, FUN = sum)
HideShow
  week treat control Difference
1    1   135     113         22
2    2   132     108         24
HideShow
#> 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)
HideShow
  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():

HideShow
colSums(chapter_1_table_1[, c("treat", "control", "Difference")])    # 267 / 221 / 46
HideShow
     treat    control Difference 
       267        221         46 
HideShow
colMeans(chapter_1_table_1[, c("treat", "control", "Difference")])   # 26.7 / 22.1 / 4.6
HideShow
     treat    control Difference 
      26.7       22.1        4.6 
HideShow
#> matches the last two rows of Table 1.1, book p. 29

1.4 — Introduction to the Fisher Tradition

Section 1.4 of the book derives two statistical tests entirely from first principles, so that the meaning of a pp 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.

1.4.2 — A Discrete Probability Example

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.

Counting rules in R

How many ways are there to choose four cups out of eight to label MF? Following the book’s reasoning, there are 8×7×6×58 \times 7 \times 6 \times 5 ways to choose four cups in a particular order:

HideShow
8 * 7 * 6 * 5
HideShow
[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 4×3×2×14 \times 3 \times 2 \times 1 ways:

HideShow
factorial(4)
HideShow
[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:

HideShow
# Equation (1.2): the number of distinct sets of four cups
(8 * 7 * 6 * 5) / (4 * 3 * 2 * 1)
HideShow
[1] 70

This quantity is the number of combinations of eight things taken four at a time, 8C4{}_{8}C_{4}. R computes combinations directly with choose(n, k):

HideShow
choose(n = 8, k = 4)
HideShow
[1] 70

The general counting rule, nCr=n!/[r!(n−r)!]{}_{n}C_{r} = n! \, / \, [r!(n – r)!], 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):

HideShow
# Equation (1.3): n! / (r! (n - r)!)
factorial(8) / (factorial(4) * factorial(8 - 4))
HideShow
[1] 70

Because only one of these 70 equally likely divisions is exactly correct, the probability of a perfect classification by chance alone is 1/701/70. This is Equation (1.1):

HideShow
# Equation (1.1): probability of being exactly correct by chance
1 / choose(n = 8, k = 4)
HideShow
[1] 0.01428571
HideShow
#> 0.01428..., the 1/70 of Equation (1.1); matches book p. 26

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:

HideShow
dim(combn(x = 8, m = 4))      # 4 rows (cups per set) by 70 columns (sets)
HideShow
[1]  4 70
HideShow
combn(x = 8, m = 4)[, 1:8]    # the first eight of the 70 possible sets
HideShow
     [,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 8P4=n!/(n−r)!{}_{8}P_{4} = n! \, / \, (n – r)!:

HideShow
factorial(8) / factorial(8 - 4)
HideShow
[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 4C3⋅4C1{}_{4}C_{3} \cdot {}_{4}C_{1}, Equation (1.4):

HideShow
# Equation (1.4): one error of each kind
choose(n = 4, k = 3) * choose(n = 4, k = 1)
HideShow
[1] 16

The probability of that near-perfect outcome is this count over the 70 possible divisions, Equation (1.5):

HideShow
# 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)
HideShow
[1] 0.2285714
HideShow
#> 0.2286..., the 16/70 = .229 of Equation (1.5); matches book p. 27

So the probability of performance at least this good—three or four correct—is the sum of the two cases, (16+1)/70≈.243(16 + 1)/70 \approx .243:

HideShow
(choose(n = 4, k = 3) * choose(n = 4, k = 1) + 1) / choose(n = 8, k = 4)
HideShow
[1] 0.2428571
HideShow
#> 0.2429..., the (16 + 1)/70 = .243 of "three or four correct"; matches book p. 27

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 nn items from NN, of which RR are “right.” That rule is the hypergeometric probability, which R provides as dhyper(). Here N=8N = 8 cups, R=4R = 4 are truly MF (m), N−R=4N – R = 4 are TF (n), and the lady selects k=4k = 4:

HideShow
# 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
HideShow
[1] 0.2285714
HideShow
dhyper(x = 4, m = 4, n = 4, k = 4)   # all four correct: 1/70 = .014
HideShow
[1] 0.01428571
HideShow
sum(dhyper(x = 3:4, m = 4, n = 4, k = 4))   # three or four correct: 17/70 = .243
HideShow
[1] 0.2428571
Fisher’s exact test in R

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:

HideShow
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
HideShow
            Actual
Guess        Milk-first Tea-first
  Milk-first          4         0
  Tea-first           0         4
HideShow
fisher.test(TeaTasting_Perfect, alternative = "greater")
HideShow

    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 pp value is 0.0143—exactly the 1/701/70 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():

HideShow
TeaTasting_Near <- rbind("Milk-first" = c(3, 1),
                         "Tea-first"  = c(1, 3))
TeaTasting_Near
HideShow
           [,1] [,2]
Milk-first    3    1
Tea-first     1    3
HideShow
fisher.test(TeaTasting_Near, alternative = "greater")
HideShow

    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 pp value is 0.2429—exactly the (16+1)/70=.243(16 + 1)/70 = .243 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.)

Effect size for the 2 × 2 table

Beyond the pp 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:

HideShow
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)
HideShow
[1] 0.5
HideShow
#> 0.50 — matches book p. 28

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:

odds ratio=p1/(1−p1)p2/(1−p2).\text{odds ratio} = \frac{p_{1} / (1 – p_{1})}{p_{2} / (1 – p_{2})}.

A small function makes this reusable. For the hypothesized success probabilities used in the power calculation below (p1=.9p_1 = .9, p2=.3p_2 = .3), the odds ratio is 21:

HideShow
odds_ratio <- function(p1, p2) (p1 / (1 - p1)) / (p2 / (1 - p2))
odds_ratio(p1 = 0.9, p2 = 0.3)
HideShow
[1] 21
Power of Fisher’s exact test (advanced)

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 θ\theta 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 θ=21\theta = 21:

HideShow
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
HideShow
[1] 21

With four cups of each kind, the only convincing outcome is perfect classification (all four, r=4r = 4). Summing the noncentral hypergeometric probabilities over the rejection region gives the power:

HideShow
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
HideShow
[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:

HideShow
(choose(4, 4) * p1^4 * (1 - p1)^0) * (choose(4, 0) * p2^0 * (1 - p2)^4)
HideShow
[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 same power in DMAR

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.

HideShow
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.

1.4.3 — Randomization Test

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 2102^{10} equally likely sign patterns; with the 5 pairs from Week 1 alone, there are 252^{5}:

HideShow
2^5
HideShow
[1] 32
HideShow
2^10
HideShow
[1] 1024
The logic, illustrated with Week 1

If the first week were the whole experiment, we would have five differences, hence 25=322^5 = 32 possible assignments of signs. The observed Week 1 differences are:

HideShow
week1_diff <- chapter_1_table_1[chapter_1_table_1$week == 1, "Difference"]
week1_diff
HideShow
[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):

HideShow
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)
HideShow
  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 pp value:

HideShow
Week1_Sums <- apply(Possible_Assignments_Week1, 1, sum)
sort(Week1_Sums, decreasing = TRUE)
HideShow
 [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
HideShow
sum(Week1_Sums >= 22)        # how many of the 32 sums reach the observed 22
HideShow
[1] 5
HideShow
mean(Week1_Sums >= 22)       # the proportion: 5/32 = .16
HideShow
[1] 0.15625
HideShow
#> 5 of 32 — matches book p. 31 (Table 1.2)

Five of the 32 assignments give a total of 22 or more, so the one-tailed probability is 5/32≈.165/32 \approx .16—not small enough to claim significance for Week 1 alone.

Figure 1.2. Distribution of possible totals of difference scores (Week 1)

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 25=322^5 = 32 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, 5/32≈.165/32 \approx .16, is the one-tailed pp value. We build the 32 totals directly from chapter_1_table_1, so the figure is reproduced exactly rather than transcribed.

HideShow
# 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.

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 5/32≈.165/32 \approx .16 that Section 1.4.3 reports for Week 1 alone.

The full ten-pair test

Listing all 210=1,0242^{10} = 1{,}024 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 +1+1 and −1-1 across the pairs; multiplying those sign patterns by the differences and summing gives one total per assignment:

HideShow
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:

HideShow
# Check: Week 1 still gives 5/32 = .16
mean(all_signflip_sums(week1_diff) >= 22)
HideShow
[1] 0.15625
HideShow
# 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
HideShow
[1] 46
HideShow
length(all_sums)                   # 1024 assignments
HideShow
[1] 1024

The one-tailed pp value is the proportion of the 1,024 totals that are at least 46:

HideShow
sum(all_sums >= observed_sum)      # 40 of the 1024 assignments
HideShow
[1] 40
HideShow
mean(all_sums >= observed_sum)     # 40/1024 = .039 (one-tailed)
HideShow
[1] 0.0390625
HideShow
#> "only 40 of 1,024, or .039" — matches book p. 31

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:

HideShow
c(greater = sum(all_sums >  observed_sum),
  equal   = sum(all_sums == observed_sum),
  less    = sum(all_sums <  observed_sum))   # 26, 14, 984
HideShow
greater   equal    less 
     26      14     984 
HideShow
#> the Sum > 46 / Sum = 46 / Sum < 46 totals of Table 1.3; matches book p. 32

Because the randomization distribution is symmetric, a two-tailed test counts totals at least as extreme as 46 in either direction, giving 80/1024≈.07880/1024 \approx .078:

HideShow
sum(abs(all_sums) >= observed_sum)     # 80
HideShow
[1] 80
HideShow
mean(abs(all_sums) >= observed_sum)    # 80/1024 = .078 (two-tailed)
HideShow
[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 same test in DMAR

The hand enumeration above is exactly what DMAR’s randomization_test_paired() automates. It enumerates all 2n2^{n} sign patterns when nn is small (here n=10n = 10, so all 1,024) and falls back to Monte Carlo sampling when nn is large. The x = control, y = treat ordering matches the book’s Treatment − Control direction:

HideShow
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 40/1024≈.03940/1024 \approx .039; the two-sided version (set alternative = "two.sided") returns the 80/1024≈.07880/1024 \approx .078 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.

A paired effect size: the probability of superiority

The pp 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:

HideShow
sum(chapter_1_table_1$treat >  chapter_1_table_1$control)    # pairs won by training: 6
HideShow
[1] 6
HideShow
sum(chapter_1_table_1$treat == chapter_1_table_1$control)    # tied pairs: 0
HideShow
[1] 0
HideShow
mean(chapter_1_table_1$treat >  chapter_1_table_1$control)   # 6 of 10 = .60
HideShow
[1] 0.6

Six of the ten pairs favor training, so the estimate is 6/10=.606/10 = .60. 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:

HideShow
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
)
HideShow

    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 pp 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 pp value (about .75) is so much larger than the .039 above.

The same effect size in DMAR

DMAR’s probability_of_superiority_paired() reports the same quantity directly:

HideShow
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.

Correspondence with the paired tt test

The book notes that a paired tt-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 tt-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 =):

HideShow
t.test(chapter_1_table_1$Difference)
HideShow

    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:

HideShow
t.test(chapter_1_table_1$treat, chapter_1_table_1$control, paired = TRUE)
HideShow

    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 t=2.14t = 2.14 on 9 degrees of freedom, with a two-tailed pp value of about .061. The book reports the matching one-tailed value, .031, which we obtain with the directional alternative:

HideShow
t.test(chapter_1_table_1$treat, chapter_1_table_1$control,
       paired = TRUE, alternative = "greater")
HideShow

    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 
HideShow
#> t = 2.14 on 9 df, one-tailed p = .031; matches book p. 32

The one-tailed tt-test pp 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 tt 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 tt-test.

1.4.5 — Toward Tests Based on Distributional Assumptions

1.4.5.2 — The Assumption of Normality

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.

Figure 1.3. Grouped frequency distribution of simple reaction times

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.

HideShow
# 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.

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).

Figure 1.4. MMPI hypochondriasis scores

A second illustration of approximate normality comes from a personality scale. This figure shows the distribution of Hypochondriasis-scale TT 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.

HideShow
# 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.

Figure 1.4. MMPI hypochondriasis scores.

The roughly 700 “Minnesota normals” produce a distribution centered near a TT 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).

Summary

This chapter’s quantitative material builds two tests from first principles so that the pp value is something we derive, not merely look up:

  • Fisher’s exact test (§1.4.2), from counting rules—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.
  • The randomization test (§1.4.3), from the 2n2^{n} equally likely sign patterns of the matched-pairs differences, with the probability of superiority—counted in base R and interval-estimated by DMAR—as its order-only effect size, and its close correspondence to the paired 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.

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 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.

References

Scroll to Top