Chapter 3: Introduction to Model Comparisons: One-Way Between-Subjects Designs

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 covers the R groundwork these notes take for granted: installing packages from CRAN, loading them, and the way the book’s data sets are named. This chapter draws on three of them — chapter_3_table_1, chapter_3_table_3, and chapter_3_table_7_raw, the last holding the raw scores behind a table the book presents in summary form. data(package = "AMCP") lists every data set in the package.

HideShow
# Load all of the packages used.
library(AMCP)           # the textbook's data sets
library(ggplot2)        # the grammar of graphics used for the book's data figures
library(dplyr)          # data manipulation
library(DMAR)           # design, measurement, and analysis
library(car)            # leveneTest() and Anova() for Type II/III tests
library(moments)        # skewness and kurtosis
library(psych)          # many functions for descriptive statistics and psychometrics
library(pwr)            # power analysis for common designs
library(gt)             # polished HTML tables
library(gtsummary)      # publication-ready regression / comparison tables
library(modelsummary)   # side-by-side model-comparison tables
library(sjPlot)         # tab_model(): mixed-model tables, including the ICC

3.5 — One-Group Situation

3.5.3 — Numerical Example

The chapter’s one-group numerical example is the WISC-R IQ data for six hyperactive children in Table 3.1 (p. 88), tested against a null value of 98. We begin with the descriptive statistics, then work the model comparison the table lays out.

Descriptive statistics in base R

Load Chapter 3, Table 1 with the following command (AMCP was loaded with the other packages above).

HideShow
data(chapter_3_table_1)

One could call upon the summary statistics of interest individually, as we do below. Note that chapter_3_table_1 is a data frame, which typically means there is more than a single variable (as above). Because of the more flexible nature of a data frame, we need to identify the variable of interest for which we want to take the summary statistics. This seems unnecessary here, but consider the more general case of multiple variables, where identifying the variable of interest is important. The functions below are commonly used functions for describing data. There are many others that can be used. For information on any of the function uses, use the ?function.name or help("") or help.search("topic of interest")

HideShow
mean(chapter_3_table_1$IQ)
HideShow
[1] 104
HideShow
median(chapter_3_table_1$IQ)
HideShow
[1] 104
HideShow
quantile(chapter_3_table_1$IQ, probs=c(.05, .25, .5, .75, .95))
HideShow
   5%   25%   50%   75%   95% 
 97.5 102.5 104.0 107.0 109.5 
HideShow
sd(chapter_3_table_1$IQ)
HideShow
[1] 4.898979
HideShow
length(chapter_3_table_1$IQ)
HideShow
[1] 6

Let’s summarize Table 3.1a in the book. Note that in the code below, MARGIN=2 indicates that margin totals across the columns are taken (MARGIN=1 would be the margin totals across rows).

HideShow
Table_3_1a <- cbind(Y=chapter_3_table_1$IQ, Parameter.Term=rep(104,
  length(chapter_3_table_1$IQ)), Error_Scores=chapter_3_table_1$IQ-104,
  Squared_Term=(chapter_3_table_1$IQ-104)^2)

# From the table, take a sum of all but the second column ("-2" ignores the second column).
apply(Table_3_1a[,-2], MARGIN=2, FUN=sum)
HideShow
           Y Error_Scores Squared_Term 
         624            0          120 
Descriptive statistics with dplyr

The same sum of squared deviations comes out of a single call to summarize() from the dplyr package: each argument names a quantity and the expression that produces it, so the whole summary is one statement rather than several.

The %>% below is a pipe. It feeds the value on its left into the function on its right as that function’s first argument, so chapter_3_table_1 %>% summarize(...) reads in the order the work is done: start with these data, then summarize them. Base R has since gained a native pipe, |>, which behaves the same way in the uses that appear on these pages.

HideShow
chapter_3_table_1 %>%
  summarize(Sum_Y = sum(IQ),
            n = n(),
            Sum_Squared_Errors = sum((IQ-104)^2))
HideShow
  Sum_Y n Sum_Squared_Errors
1   624 6                120
The model comparison and the FF test

Here we find FF as done in Table 3.1.

HideShow
Values <- chapter_3_table_1 %>%
  summarize(Error_F = sum((IQ-mean(IQ))^2),
            df_F = n()-1,
            Error_R = sum((IQ-98)^2),
            df_R = n(),
            F = ((Error_R - Error_F)/(df_R - df_F))/(Error_F/df_F))

# Print the whole row, then the F column. (A bare `F` would print the built-in
# constant FALSE, since R reads `F` as an abbreviation for FALSE; we want the
# column we just computed.)
Values
HideShow
  Error_F df_F Error_R df_R F
1     120    5     336    6 9
HideShow
Values$F
HideShow
[1] 9
HideShow
#> matches book p. 88 (Table 3.1): E_F = 120, E_R = 336, F = 216/24 = 9

Linear models, as discussed in the text, can be implemented in R using the lm() function. Here we use the lm() function in a non-standard way to illustrate the idea of model comparisons. Additionally, we use the anova() function in order to compare two lm(). Note that the anova() function requires that the dependent variable be named the same in the two competing models, which is why we form IQ.1 and IQ.2 as we do below.

HideShow
# Define two data frames, IQ.1 and IQ.2, which is simply the data from Chapter 3, Table 1
IQ_1 = IQ_2 <- chapter_3_table_1

# Reassign `IQ` from the IQ.2 data set as the IQ scores minus the value of 98, which is
# the null.
IQ_2$IQ <- IQ_2$IQ-98

# Fit a linear model in which only the intercept (i.e., the 1) is estimated, which is the
# mean in this context, using the IQ.1 data set.
Full <- lm(IQ ~ 1, data=IQ_1)

# Fit a linear model in which there is no intercept term (i.e., the -1).
Restricted <- lm(IQ ~ -1, data=IQ_2)

# Now, perform the model comparisons. It is important that the two data sets use the same
# name for the dependent variable.
anova(Restricted, Full)
HideShow
Analysis of Variance Table

Model 1: IQ ~ -1
Model 2: IQ ~ 1
  Res.Df RSS Df Sum of Sq  F Pr(>F)  
1      6 336                         
2      5 120  1       216  9 0.0301 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The critical value from an FF-distribution can be found using the qf() function, in which the quantile of interest is specified (e.g., .95) and the numerator and denominator degrees of freedom. Generically, qf() is used as qf(1-alpha, df1, df2). For our example:

HideShow
qf(.95, 1, 5)
HideShow
[1] 6.607891

The pp-value from an FF-test can be found using the pf() function, in which the observed FF-value and degrees of freedom are supplied as arguments. Generically, pf() is used as 1-pf(F, df1, df2) (to obtain the area greater than the observed FF-value). For our example:

HideShow
1-pf(9, 1, 5)
HideShow
[1] 0.03009925
HideShow
# Alternatively
pf(9, 1, 5, lower.tail = FALSE)
HideShow
[1] 0.03009925
The equivalent tt test

As noted in the text, a tt-test can be done. In R, the t.test() function with the null values to test of mu=98 specified can be used.

HideShow
t.test(chapter_3_table_1$IQ, mu=98)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.0301
alternative hypothesis: true mean is not equal to 98
95 percent confidence interval:
  98.85884 109.14116
sample estimates:
mean of x 
      104 

The t.test() function is very general. It can be used for single-sample tt-tests, paired samples tt-test, and independent-samples tt-tests based on the way in which the arguments are specified. To learn more about the various options or a function, use the help() function. Equivalently, a question mark immediately followed by the function for which you want to see the help file can be used. Either one opens the help page in your own R session, so the two lines below are shown but not run here.

HideShow
help(t.test)
?t.test

Doing a tt-test step-by-step can be done as follows, where we first define a variable called IQ to make the code easier to follow.

HideShow
IQ <- chapter_3_table_1$IQ
Mean_IQ <- mean(IQ)
s_IQ <- sd(IQ)
n <- length(IQ)
(Mean_IQ - 98)/(s_IQ/sqrt(n))
HideShow
[1] 3

The critical value or values from a tt-distribution can be found using the qt() function, in which the quantiles of interest are specified (e.g., .025 and .975 for a two-sided test; .95 for a one-sided test). For example

HideShow
# For a one-sided test using alpha=.05
qt(.95, 5)
HideShow
[1] 2.015048
HideShow
# For a two-sided test using alpha=.05
qt(c(.025, .975), 5)
HideShow
[1] -2.570582  2.570582

The pp-value from a tt-test can be found using the pt() function, in which the observed tt-value and degrees of freedom are supplied as arguments. For a two-sided pp-value, the pt() function can be used generically as 2*(1-pt(abs(t), df)), where the absolute value is used for the observed tt-value.

HideShow
# For a two-sided p-value
2*(1-pt(abs(3), 5))
HideShow
[1] 0.03009925

For a one-sided pp-value the pt() function is used differently based on the alternative hypothesis that is specified. For an alternative hypothesis of “<”, only the area to the left of the observed tt-value is needed, so pt is used as pt(t, df), which returns the cumulative probability. It is important that the absolute value function (i.e., abs()) is not used for single-sided tests.

HideShow
pt(3, 5)
HideShow
[1] 0.9849504
HideShow
# The above differs considerably from, say, an observed negative t-value and a "<"
# alternative hypothesis.
pt(-3, 5)
HideShow
[1] 0.01504962

Had a “>” alternative hypothesis been specified, the pt() function would be used as 1-pt(t, df), which returns the area more extreme than the observed tt-value. Again, it is important that the absolute value function (i.e., abs()) is not used for single-sided tests.

HideShow
1-pt(3, 5)
HideShow
[1] 0.01504962
HideShow
# The above differs considerably from, say, an observed negative t-value and a ">"
# alternative hypothesis.
1-pt(-3, 5)
HideShow
[1] 0.9849504

3.7 — The General Case of One-Way Designs

3.7.2 — Numerical Example

The chapter’s one-way numerical example is the mood-induction study of Table 3.3: 30 participants are assigned to a pleasant, neutral, or unpleasant mood induction, and each gives a single global-affect rating on a 7-point scale. Table 3.4 (p. 98) works the analysis of variance for these data, which we reproduce below after first preparing and plotting them.

Loading and viewing the data

We begin with Table 3.3, the data upon which Figure 3.1 is based. Calling the object by name returns it, so we can see what we have.

HideShow
data(chapter_3_table_3)
chapter_3_table_3
HideShow
   Condition Rating
1          1      6
2          1      5
3          1      4
4          1      7
5          1      7
6          1      5
7          1      5
8          1      7
9          1      7
10         1      7
11         2      5
12         2      4
13         2      4
14         2      3
15         2      4
16         2      3
17         2      4
18         2      4
19         2      4
20         2      5
21         3      3
22         3      3
23         3      4
24         3      4
25         3      4
26         3      3
27         3      1
28         3      2
29         3      2
30         3      4

To learn the structure of the data, the str() function can be used. Importantly, here, we see that Condition is treated as an integer (a number).

HideShow
str(chapter_3_table_3)
HideShow
'data.frame':   30 obs. of  2 variables:
 $ Condition: int  1 1 1 1 1 1 1 1 1 1 ...
 $ Rating   : int  6 5 4 7 7 5 5 7 7 7 ...

The above can also be seen by using the class() function, which shows that Condition is a numeric variable.

HideShow
class(chapter_3_table_3$Condition)
HideShow
[1] "integer"

We can convert Condition into a factor, so that it is explicitly recognized as a grouping variable, using the as.factor() function and redefining the Condition variable.

HideShow
chapter_3_table_3$Condition <- as.factor(chapter_3_table_3$Condition)
class(chapter_3_table_3$Condition)
HideShow
[1] "factor"
Boxplots of the three conditions

Every figure in these notes is drawn with ggplot2. A ggplot is built up in layers: a call to ggplot() names the data and maps variables to positions, and one or more geom_*() layers say how to draw them. The simplest box-and-whiskers plot of the ratings by condition is a single geom_boxplot() layer.

HideShow
ggplot(chapter_3_table_3, aes(x = Condition, y = Rating)) +
  geom_boxplot()

Axis labels and a title are added with labs().

HideShow
ggplot(chapter_3_table_3, aes(x = Condition, y = Rating)) +
  geom_boxplot() +
  labs(title = "Box and whiskers plot of affect rating by group",
       x = "Group", y = "Global affect rating")

The conditions are still labeled 1, 2, and 3. Spelling the levels out makes the figure readable on its own. We map each code to its name with case_when() so the correspondence is written out rather than left to the order of a vector, then call factor() only to fix the order in which the levels appear.

HideShow
mood <- chapter_3_table_3 |>
  mutate(Condition = case_when(
    Condition == 1 ~ "Pleasant",
    Condition == 2 ~ "Neutral",
    Condition == 3 ~ "Unpleasant"
  )) |>
  mutate(Condition = factor(Condition,
    levels = c("Pleasant", "Neutral", "Unpleasant")))

ggplot(mood, aes(x = Condition, y = Rating)) +
  geom_boxplot() +
  labs(title = "Box and whiskers plot of affect rating by group",
       x = "Group", y = "Global affect rating")

Adding the individual scores with geom_point() shows what each box summarizes.

HideShow
ggplot(mood, aes(x = Condition, y = Rating)) +
  geom_boxplot(outlier.shape = NA) +
  geom_point() +
  labs(title = "Box and whiskers plot of affect rating by group",
       x = "Group", y = "Global affect rating")

Because several participants gave the same rating, those points fall on top of one another and cannot be counted. “Jittering” them (literally, shifting each one slightly) makes the distribution within each group visible. That is what the book’s Figure 3.1 does, which we draw next.

Figure 3.1. Individual global-affect scores in three treatment groups

This figure shows every individual score, grouped by condition, with a box summarizing each group. Plotting the raw points — jittered horizontally so ties are visible — is the figure’s purpose: it shows the spread within each group, not just the group means.

HideShow
set.seed(113)  # reproducible jitter
ggplot(mood, aes(x = Condition, y = Rating)) +
  geom_boxplot(width = 0.55, fill = "white",
               color = "black", outlier.shape = NA) +
  geom_jitter(width = 0.12, height = 0, size = 2.3, alpha = 0.8,
              color = "#0C2340") +
  scale_y_continuous(breaks = 1:7, limits = c(1, 7)) +
  labs(x = "Treatment group", y = "Global affect rating")
Figure 3.1. Individual scores on a 7-point rating scale of global affect in three treatment groups.

Figure 3.1. Individual scores on a 7-point rating scale of global affect in three treatment groups.

The pleasant-induction scores sit high (mostly 5 to 7), the unpleasant-induction scores low (mostly 1 to 4), and the neutral group in between — the pattern the one-way FF test formalizes below.

Group descriptive statistics with dplyr

Numeric summaries can be obtained with the summary() function. One way to do this is to select the rows of interest (i.e., the groups) by using logical statements. Later we explore other ways of doing this. Note that, however, the percentiles (or quantiles) that are given are from but one way of calculating percentiles (or quantiles). See ?quantile for more information on how R makes such computations (there are, in fact, nine different algorithms that R can use, with the appropriate options selected).

HideShow
summary(chapter_3_table_3[chapter_3_table_3[,"Condition"]==1, "Rating"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    4.0     5.0     6.5     6.0     7.0     7.0 
HideShow
summary(chapter_3_table_3[chapter_3_table_3[,"Condition"]==2, "Rating"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
      3       4       4       4       4       5 
HideShow
summary(chapter_3_table_3[chapter_3_table_3[,"Condition"]==3, "Rating"])
HideShow
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    2.25    3.00    3.00    4.00    4.00 
HideShow
sd(chapter_3_table_3[chapter_3_table_3[,"Condition"]==1, "Rating"])
HideShow
[1] 1.154701
HideShow
sd(chapter_3_table_3[chapter_3_table_3[,"Condition"]==2, "Rating"])
HideShow
[1] 0.6666667
HideShow
sd(chapter_3_table_3[chapter_3_table_3[,"Condition"]==3, "Rating"])
HideShow
[1] 1.054093
Computations for the one-way ANOVA

We used the summarize() function from the dplyr package earlier. A wonderful function within dplyr is the group_by() function, which does the summarizing as demonstrated before, but it does so by a grouping factor. For us, the grouping factor is Condition, which identifies the levels of the group (i.e., Condition). We can very simply replicate Table 3.4 (something that takes some work in other programs).

HideShow
Summary_Mood <- chapter_3_table_3 %>%
  group_by(Condition) %>%
  summarize(Sum_Y = sum(Rating),
            Y_bar = mean(Rating),
            Sum_Squared_Errors = sum((Rating-mean(Rating))^2),
            n = n())

Summary_Mood
HideShow
# A tibble: 3 × 5
  Condition Sum_Y Y_bar Sum_Squared_Errors     n
  <fct>     <int> <dbl>              <dbl> <int>
1 1            60     6                 12    10
2 2            40     4                  4    10
3 3            30     3                 10    10
HideShow
(a <- length(unique(chapter_3_table_3$Condition)))
HideShow
[1] 3
HideShow
(N <- length(chapter_3_table_3$Rating))
HideShow
[1] 30
HideShow
(E_F <- sum(Summary_Mood$Sum_Squared_Errors))
HideShow
[1] 26
HideShow
(E_R <- sum((chapter_3_table_3$Rating - mean(chapter_3_table_3$Rating))^2))
HideShow
[1] 72.66667
HideShow
(SS_Between <- E_R - E_F)
HideShow
[1] 46.66667
HideShow
(MS_Between <- SS_Between/(a-1))
HideShow
[1] 23.33333
HideShow
(MS_Within <- E_F/(N-a))
HideShow
[1] 0.962963
HideShow
(df_F <- df_Within <- N-a)
HideShow
[1] 27
HideShow
(df_R <- N-1)
HideShow
[1] 29
HideShow
(df_Between <- df_R-df_F)
HideShow
[1] 2
HideShow
# Named F_obs rather than F: R reads a bare `F` as an abbreviation for FALSE,
# so assigning to it would mask the built-in constant for the rest of the session.
(F_obs <- ((E_R - E_F)/(df_R-df_F))/(E_F/df_F))
HideShow
[1] 24.23077
HideShow
# Or
((E_R - E_F)/df_Between)/(E_F/df_Within)
HideShow
[1] 24.23077
HideShow
# Or,
MS_Between/MS_Within
HideShow
[1] 24.23077
HideShow
# Critical value
qf(.95, df_Between, df_Within)
HideShow
[1] 3.354131
HideShow
# p-value
1-pf(F_obs, df_Between, df_Within)
HideShow
[1] 9.421379e-07

As a direct check that these intermediate quantities match the book’s Table 3.4, we plug the numbers into the formula.

HideShow
c(E_F = E_F, E_R_minus_E_F = SS_Between, MS_Between = MS_Between,
  MS_Within = MS_Within, F = F_obs)
HideShow
          E_F E_R_minus_E_F    MS_Between     MS_Within             F 
    26.000000     46.666667     23.333333      0.962963     24.230769 
HideShow
#> matches book p. 98 (Table 3.4): E_F = SS_W = 26, SS_B = 46.67,
#> MS_B = 23.33, MS_W = 0.963, F = 24.23

The above showed the step-by-step how-to that mimics the text. In R, a one-way ANOVA can be done as follows (recalling that we already defined Condition as a factor). In the code below the aov() function fits an ANOVA model but summary() provides a summary of an aov() (and many other) objects, as we will see.

HideShow
summary(aov(Rating ~ Condition, data=chapter_3_table_3))
HideShow
            Df Sum Sq Mean Sq F value   Pr(>F)    
Condition    2  46.67  23.333   24.23 9.42e-07 ***
Residuals   27  26.00   0.963                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Note that, had we not already defined Condition as a factor, it can be done within the aov() function as follows. Specification of the factor is important, otherwise use of the aov() and summary() functions will produce results for a different type of analysis.

HideShow
summary(aov(Rating ~ as.factor(Condition), data=chapter_3_table_3))
HideShow
                     Df Sum Sq Mean Sq F value   Pr(>F)    
as.factor(Condition)  2  46.67  23.333   24.23 9.42e-07 ***
Residuals            27  26.00   0.963                     
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The two models side by side

This is the first one-way between-subjects design in the book, so it is worth seeing the model comparison the FF test actually performs. The restricted model estimates a single grand mean (Rating ~ 1); the full model estimates a separate mean for each condition (Rating ~ Condition). The FF test asks whether the extra two parameters of the full model reduce error enough to be worth keeping.

HideShow
Restricted_Model <- lm(Rating ~ 1, data=chapter_3_table_3)         # grand mean only
Full_Model       <- lm(Rating ~ Condition, data=chapter_3_table_3) # group means

# The error sums of squares of these two models are E_R and E_F from the
# by-hand table above, and anova() returns the same F as summary(aov()).
anova(Restricted_Model, Full_Model)
HideShow
Analysis of Variance Table

Model 1: Rating ~ 1
Model 2: Rating ~ Condition
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1     29 72.667                                  
2     27 26.000  2    46.667 24.231 9.421e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

A side-by-side table makes the two models easy to compare. With modelsummary, each model is in its own column with standard errors in parentheses and the fit statistics at the foot. The full model’s residual deviance is E_F (26) and the restricted model’s is E_R (72.667), the same error terms compared by hand.

HideShow
modelsummary(
  list("Restricted (grand mean)" = Restricted_Model,
       "Full (group means)"      = Full_Model),
  estimate  = "{estimate}",
  statistic = "({std.error})",   # standard errors in parentheses, APA style
  gof_map   = c("nobs", "aic", "bic", "logLik"),
  output    = "gt"
)
Restricted (grand mean) Full (group means)
(Intercept) 4.333 6.000
(0.289) (0.310)
Condition2 -2.000
(0.439)
Condition3 -3.000
(0.439)
Num.Obs. 30 30
AIC 115.7 88.8
BIC 118.5 94.4
Log.Lik. -55.838 -40.422

The full model’s coefficients as a gtsummary regression table. With the default (treatment) contrasts the intercept is the pleasant-condition mean (6), and each slope is a group mean’s deviation from it (neutral, 4−6=−24 – 6 = -2; unpleasant, 3−6=−33 – 6 = -3).

HideShow
tbl_regression(Full_Model, intercept = TRUE)
Characteristic Beta 95% CI p-value
(Intercept) 6.0 5.4, 6.6 <0.001
Condition


    1 — —
    2 -2.0 -2.9, -1.1 <0.001
    3 -3.0 -3.9, -2.1 <0.001
Abbreviation: CI = Confidence Interval

The same analysis as an APA-style ANOVA table built with gt: Source, SSSS, dfdf, MSMS, FF, pp, and partial η2\eta^2. (For a one-way design partial η2\eta^2 equals η2=SSB/SST\eta^2 = SS_B / SS_T, the full model’s R2R^2.)

HideShow
aov_fit <- aov(Rating ~ Condition, data=chapter_3_table_3)
aov_df  <- as.data.frame(summary(aov_fit)[[1]])
ss_res  <- aov_df["Residuals", "Sum Sq"]
data.frame(
  Source = c("Condition (Between)", "Within (Error)"),
  SS     = aov_df[, "Sum Sq"],
  df     = aov_df[, "Df"],
  MS     = aov_df[, "Mean Sq"],
  Fstat  = aov_df[, "F value"],
  p      = aov_df[, "Pr(>F)"],
  # Partial eta-squared: effect SS over effect-plus-error SS.
  peta   = c(aov_df["Condition", "Sum Sq"] /
               (aov_df["Condition", "Sum Sq"] + ss_res), NA_real_)
) |>
  gt() |>
  fmt_number(columns = c(SS, MS, Fstat), decimals = 2) |>
  fmt_number(columns = peta, decimals = 3) |>
  fmt_number(columns = p,    decimals = 4) |>
  sub_missing(missing_text = "") |>
  cols_label(Fstat = md("*F*"), p = md("*p*"),
             peta = md("Partial &eta;<sup>2</sup>")) |>
  tab_header(title = md("**Table 3.4**. Analysis of Variance for Global Affect Rating")) |>
  cols_align(align = "center", columns = -Source)
Table 3.4. Analysis of Variance for Global Affect Rating
Source SS df MS F p Partial η2
Condition (Between) 46.67 2 23.33 24.23 0.0000 0.642
Within (Error) 26.00 27 0.96


3.9 — Measures of Effect

3.9.1 — Measures of Effect Size

3.9.1.2 — Confidence Intervals

To compute a confidence interval, in a step-by-step fashion, we can create objects of the relevant values, where MOE is margin of error.

HideShow
alpha <- .05
n <- 6
Y_bar <- 104
s <- sqrt(24)
s_Y_bar <- s/sqrt(n)
MOE <- qt(1-.05/2, n-1)*s_Y_bar
Y_bar - MOE
HideShow
[1] 98.85884
HideShow
Y_bar + MOE
HideShow
[1] 109.1412
HideShow
#> 98.86, 109.14 — matches book p. 108

Recall that earlier we used the t.test() function for the test of the null hypothesis that IQ had a mean of 98. In particular, we did the following, which, as part of the output, also provides the 95% confidence interval.

HideShow
t.test(chapter_3_table_1$IQ, mu=98)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.0301
alternative hypothesis: true mean is not equal to 98
95 percent confidence interval:
  98.85884 109.14116
sample estimates:
mean of x 
      104 

Note that use of the t.test() function for purposes of obtaining a confidence interval does not depend, in any way, on the null value that is specified. For example, had the null value been 100, the confidence interval is unchanged.

HideShow
t.test(chapter_3_table_1$IQ, mu=100)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 2, df = 5, p-value = 0.1019
alternative hypothesis: true mean is not equal to 100
95 percent confidence interval:
  98.85884 109.14116
sample estimates:
mean of x 
      104 

Further, note that a different confidence level can be specified with the additional argument of conf.level = 0.95. For example, a 99% confidence interval can be obtained as

HideShow
t.test(chapter_3_table_1$IQ, mu=98, conf.level = 0.99)
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.0301
alternative hypothesis: true mean is not equal to 98
99 percent confidence interval:
  95.93571 112.06429
sample estimates:
mean of x 
      104 

Also note that a single-sided confidence interval, based on the alternative hypothesis of interest, can be obtained as the following if the alternative hypothesis is “less than”

HideShow
t.test(chapter_3_table_1$IQ, mu=98, alternative="less")
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.985
alternative hypothesis: true mean is less than 98
95 percent confidence interval:
     -Inf 108.0301
sample estimates:
mean of x 
      104 

A single sided confidence-interval for an alternative hypothesis of “greater than” can be obtained as

HideShow
t.test(chapter_3_table_1$IQ, mu=98, alternative="greater")
HideShow

    One Sample t-test

data:  chapter_3_table_1$IQ
t = 3, df = 5, p-value = 0.01505
alternative hypothesis: true mean is greater than 98
95 percent confidence interval:
 99.9699     Inf
sample estimates:
mean of x 
      104 

In this section of the book, the confidence interval for the two-independent group tt-test is done using data based on summary statistics (i.e., the Brown and Miller, 1993 example). This data is not presented in the text, as it was not presented in the article. Suppose, however, that one wanted to test the hypothesis that two independent groups had the same mean and/or they wanted to form a confidence interval for the population mean differences. Here, we will create a data set (rather than reading one from AMCP) to show how one might create a data set directly in R. The scores below are actually the scores from Groups 1 and 2 from Chapter 3, Table 3. We type in the data simply to illustrate how one might (though there are different ways) form a data set in R. Below is just one of many ways data can be entered into R.

HideShow
Group_1 <- cbind(Group=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), Score=c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7))
Group_2 <- cbind(Group=c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2), Score=c(5, 4, 4, 3, 4, 3, 4, 4, 4, 5))
Data <- as.data.frame(rbind(Group_1, Group_2))
Data$Group <- as.factor(Data$Group)

Another way to enter the data above is as follows.

HideShow
Data2 <- cbind(Group=as.factor(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)),
                  Score=c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7, 5, 4, 4, 3, 4, 3, 4, 4, 4, 5))

Yet another way uses the rep() function, which replicates a value the specified number of times.

HideShow
Data3 <- cbind(Group=as.factor(c(rep(1, 10), rep(2, 10))),
                  Score=c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7, 5, 4, 4, 3, 4, 3, 4, 4, 4, 5))

Now that we have data from two independent groups, we can perform a two-group tt-test and obtain the confidence interval as follows. Note that this tt-test does not assume homogeneity of variance, which we show momentarily.

HideShow
t.test(Score~Group, data=Data)
HideShow

    Welch Two Sample t-test

data:  Score by Group
t = 4.7434, df = 14.4, p-value = 0.0002915
alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
95 percent confidence interval:
 1.09803 2.90197
sample estimates:
mean in group 1 mean in group 2 
              6               4 

Alternatively, the above tt-test can be modified so that it assumes homogeneity of variance, as we have done thus far in the book for comparing means among some number of groups. This is accomplished in R using the additional specification of var.equal=TRUE.

HideShow
t.test(Score~Group, data=Data, var.equal=TRUE)
HideShow

    Two Sample t-test

data:  Score by Group
t = 4.7434, df = 18, p-value = 0.0001623
alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
95 percent confidence interval:
 1.114173 2.885827
sample estimates:
mean in group 1 mean in group 2 
              6               4 

The above tt-test can also be specified without the use of the data argument, but by using two matrices of scores (recall that we defined two vectors of the scores when we first created this data set). Note that you must select only the Score column (otherwise the group identifier will also be used)

HideShow
t.test(Group_1[,"Score"], Group_2[,"Score"], var.equal=TRUE)
HideShow

    Two Sample t-test

data:  Group_1[, "Score"] and Group_2[, "Score"]
t = 4.7434, df = 18, p-value = 0.0001623
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 1.114173 2.885827
sample estimates:
mean of x mean of y 
        6         4 

Had the matrix of data for Group 1 and Group 2 been specified as simply a vector of scores, we would implement a tt-test as

HideShow
group_1 <- c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7)
group_2 <- c(5, 4, 4, 3, 4, 3, 4, 4, 4, 5)
t.test(group_1, group_2, var.equal=TRUE)
HideShow

    Two Sample t-test

data:  group_1 and group_2
t = 4.7434, df = 18, p-value = 0.0001623
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 1.114173 2.885827
sample estimates:
mean of x mean of y 
        6         4 

3.9.1.4 — The Standardized Difference Between Means

Brown and Miller’s treatment and control groups each had 13 participants. The mean difference is standardized by the pooled within-group standard deviation for dd, or by the control standard deviation for dCd_C (book p. 111).

HideShow
mean_diff <- 60.9 - 18.5
# Equal group sizes give the two sample variances equal weight.
d_pooled  <- mean_diff / sqrt((778.41 + 2756.25) / 2)
d_control <- mean_diff / sqrt(2756.25)
c(d = d_pooled, d_C = d_control)
HideShow
       d      d_C 
1.008572 0.807619 
HideShow
#> 1.0086 and 0.8076 — matches book p. 111.

For Equation 3.86, DMAR applies the small-sample correction using the degrees of freedom for the chosen standardizer.

HideShow
DMAR::smd(mean_1 = 60.9, mean_2 = 18.5, s_1 = sqrt(778.41),
          s_2 = sqrt(2756.25), n_1 = 13, n_2 = 13, unbiased = TRUE)
term value
smd 0.977
HideShow
smd_c(mean_T = 60.9, mean_C = 18.5, s_C = sqrt(2756.25),
      n_C = 13, unbiased = TRUE)
term value
smd_c 0.756
HideShow
#> 0.7559 for the corrected control-standardized difference (book p. 112).

3.9.1.5 — Confidence Intervals for Standardized Differences Between Means

DMAR inverts the noncentral tt distribution for both standardizers. The intervals below assume independent normal groups with equal population variances. Using the control standard deviation alone gives 12 degrees of freedom for that interval, compared with 24 for the pooled interval.

HideShow
ci_smd(smd = d_pooled, n_1 = 13, n_2 = 13, conf_level = 0.95)
term value
ci_lower 0.180
smd 1.009
ci_upper 1.819

Confidence level: 95%

HideShow
#> 95% CI [0.1799, 1.8188] for the pooled-standardized effect (book p. 114).
ci_smd_c(smd_c = d_control, n_C = 13, n_E = 13, conf_level = 0.95)
term value
ci_lower -0.039
smd_c 0.808
ci_upper 1.626

Confidence level: 95%

Figure 3.2. Noncentral tt distributions at the confidence limits

Section 3.9 forms a confidence interval for a standardized mean difference by inverting the noncentral-tt distribution. Using the Brown and Miller (1993) two-group example (n1=n2=13n_1 = n_2 = 13, observed t=F=6.612=2.5714t = \sqrt{F} = \sqrt{6.612} = 2.5714), the limits of the 95% confidence interval for the noncentrality parameter are the two values whose noncentral-tt distributions place the observed tt at their 2.5th and 97.5th percentiles. The upper axis expresses each possible tt as a sample standardized mean difference dd. The same conversion takes the confidence limits for λ\lambda to limits for the population effect δ\delta.

HideShow
# Two-group example with an observed t statistic of 2.5714.
n1 <- 13; n2 <- 13; nu <- n1 + n2 - 2
t_obs <- 2.5714
per_d <- sqrt((n1 * n2) / (n1 + n2))   # t = d * per_d; lambda = delta * per_d

lims <- ci_nc_t(ncp = t_obs, df = nu, conf_level = 0.95)
ncp_low <- lims$value[lims$term == "ci_lower"]
ncp_up  <- lims$value[lims$term == "ci_upper"]

x <- seq(-4, 13, by = 0.01)
dens <- rbind(
  data.frame(t = x, density = dt(x, df = nu, ncp = ncp_low),
             limit = "Lower"),
  data.frame(t = x, density = dt(x, df = nu, ncp = ncp_up),
             limit = "Upper")
)

ggplot(dens, aes(t, density, color = limit)) +
  geom_line(linewidth = 0.9) +
  geom_vline(xintercept = t_obs, color = "#0C2340",
             linewidth = 0.8) +
  annotate("text", x = t_obs, y = max(dens$density) * 1.02,
           label = sprintf("italic(t)[plain(obs)] == %.2f", t_obs), parse = TRUE,
           color = "#0C2340", hjust = -0.12, vjust = 0, size = 3.3) +
  scale_color_brewer(
    palette = "Dark2", breaks = c("Lower", "Upper"),
    labels = as.expression(list(
      bquote(italic("λ")[plain(L)] == .(round(ncp_low, 2))),
      bquote(italic("λ")[plain(U)] == .(round(ncp_up, 2)))
    ))
  ) +
  scale_x_continuous(
    name = expression(paste("Noncentral ", italic(t), " value")),
    sec.axis = sec_axis(~ . / per_d,
                        name = expression("Standardized mean difference," ~ italic(d)))
  ) +
  labs(
    subtitle = expression("95% confidence limits for the noncentrality parameter" ~ italic("λ")),
    y = "Density", color = NULL
  ) +
  theme(legend.position = "top")
Figure 3.2. Noncentral \(t\) distributions at the limits of a 95% confidence interval for the noncentrality parameter (Brown & Miller, 1993).

Figure 3.2. Noncentral tt distributions at the limits of a 95% confidence interval for the noncentrality parameter (Brown & Miller, 1993).

On the lower distribution the observed tt sits at the 97.5th percentile and on the upper distribution at the 2.5th percentile; rescaled to δ\delta the limits are about .18 and 1.82, the 95% confidence interval the book reports.

A two-group contrast in the mood-induction data

To anchor the standardized mean difference to data we have at hand, we take the Pleasant-versus-Unpleasant contrast from the mood-induction example (Table 3.3). Two standardizers are in play, and it is worth keeping them apart: the analysis of variance pools all three groups, giving MSW\sqrt{MS_W}, whereas a two-group dd pools only the two groups being compared. We compute both in base R.

HideShow
# Recover the three groups from the mood data.
pleasant   <- chapter_3_table_3$Rating[chapter_3_table_3$Condition == 1]
neutral    <- chapter_3_table_3$Rating[chapter_3_table_3$Condition == 2]
unpleasant <- chapter_3_table_3$Rating[chapter_3_table_3$Condition == 3]

# The analysis of variance's pooled within-group SD: sqrt(MS_W), all three groups.
E_F  <- sum((pleasant   - mean(pleasant))^2)   +
        sum((neutral    - mean(neutral))^2)    +
        sum((unpleasant - mean(unpleasant))^2)
df_F <- length(chapter_3_table_3$Rating) - 3
sd_pooled <- sqrt(E_F / df_F)
sd_pooled
HideShow
[1] 0.9813068
HideShow
# The Pleasant-minus-Unpleasant difference standardized by that within-group SD.
smd_value <- (mean(pleasant) - mean(unpleasant)) / sd_pooled
smd_value
HideShow
[1] 3.057148

The contrast itself is an ordinary two-group tt test, which base R performs with t.test(). Pooling only the two groups being compared, Cohen’s dd is the observed tt rescaled by the group sizes, d=t1/n1+1/n2d = t\sqrt{1/n_1 + 1/n_2}.

HideShow
n_g  <- length(pleasant)
df_t <- 2 * n_g - 2

Pleasant_vs_Unpleasant <- t.test(
  x           = pleasant,
  y           = unpleasant,
  alternative = "two.sided",
  var.equal   = TRUE,
  conf.level  = 0.95
)
Pleasant_vs_Unpleasant
HideShow

    Two Sample t-test

data:  pleasant and unpleasant
t = 6.0678, df = 18, p-value = 9.812e-06
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 1.961276 4.038724
sample estimates:
mean of x mean of y 
        6         3 
HideShow
t_obs <- unname(Pleasant_vs_Unpleasant$statistic)
t_obs
HideShow
[1] 6.067799
HideShow
d_two_group <- t_obs * sqrt(1 / n_g + 1 / n_g)
d_two_group
HideShow
[1] 2.713602

DMAR can recover the two-group estimate directly from the scores and give a 95% confidence interval for the corresponding population effect.

HideShow
DMAR::smd(group_1 = pleasant, group_2 = unpleasant)
term value
smd 2.714
HideShow
ci_smd(ncp = t_obs, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
ci_lower 1.453
smd 2.714
ci_upper 3.936

Confidence level: 95%

HideShow
#> d = 2.714, 95% CI [1.453, 3.936].

# ci_smd() also accepts the standardized mean difference itself, which is often
# all a published report provides; the result is the same.
ci_smd(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
ci_lower 1.453
smd 2.714
ci_upper 3.936

Confidence level: 95%

Under independent normal outcomes with a common variance, the standardized mean difference also gives the proportion of the Pleasant population above the Unpleasant mean and the probability that a randomly chosen Pleasant score exceeds a randomly chosen Unpleasant score. The two-group intervals use the same two-group standardizer and sample sizes as the preceding calculation.

HideShow
pnorm(d_two_group)
HideShow
[1] 0.9966722
HideShow
pnorm(d_two_group / sqrt(2))
HideShow
[1] 0.9724956
HideShow
1 / (2 * pnorm(d_two_group / sqrt(2)) - 1)  # number needed to treat
HideShow
[1] 1.058211
HideShow
proportion_of_superiority(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
smd 2.714
proportion_of_superiority 0.997
smd_ci_lower 1.453
smd_ci_upper 3.936
ci_lower 0.927
ci_upper 1.000

Confidence level: 95%

HideShow
cles(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
smd 2.714
cles 0.972
smd_ci_lower 1.453
smd_ci_upper 3.936
cles_ci_lower 0.848
cles_ci_upper 0.997

Confidence level: 95%

HideShow
nnt_from_smd(smd = d_two_group, n_1 = n_g, n_2 = n_g, conf_level = 0.95)
term value
smd 2.714
srd 0.945
nnt 1.058
smd_ci_lower 1.453
smd_ci_upper 3.936
nnt_ci_lower 1.005
nnt_ci_upper 1.437
srd_ci_lower 0.696
srd_ci_upper 0.995

Confidence level: 95%

HideShow
#> The first two point estimates are 0.997 and 0.972.

For illustration, take the observed two-group value as the assumed population effect in a future study of the same size. DMAR then gives the exact sampling variance and expected value of dd under that assumption.

HideShow
# Large-sample variance approximation and approximate bias-correction factor
2 / n_g + d_two_group^2 / (2 * df_t)
HideShow
[1] 0.4045455
HideShow
1 - 3 / (4 * df_t - 1)
HideShow
[1] 0.9577465
HideShow
var_smd(true_smd = d_two_group, n_1 = n_g, n_2 = n_g)
term value
var_smd_exact 0.480
var_smd_approx 0.405
HideShow
expected_smd(true_smd = d_two_group, n_1 = n_g, n_2 = n_g)
true_smd n_1 n_2 expected_smd bias j_correction
2.714 10 10 2.834 0.120 0.958

3.9.1.6 — Standardized Effects, the Signal-to-Noise Ratio, and Confidence Intervals for ff

Cohen’s ff by hand

The interval above is for the square root of the signal-to-noise ratio, which is Cohen’s ff. The point estimate needs no package at all: ff is the standard deviation of the group means, taking aa rather than a−1a – 1 as the denominator, divided by the within-group standard deviation MSW\sqrt{MS_W}.

HideShow
# Group means and the within-group mean square (the pooled within-cell variance):
group_stats <- chapter_3_table_3 %>%
  group_by(Condition) %>%
  summarize(n = n(), mean = mean(Rating), sd = sd(Rating), .groups = "drop")
group_stats
HideShow
# A tibble: 3 × 4
  Condition     n  mean    sd
  <fct>     <int> <dbl> <dbl>
1 1            10     6 1.15 
2 2            10     4 0.667
3 3            10     3 1.05 
HideShow
ms_w <- E_F / df_F
ms_w
HideShow
[1] 0.962963
HideShow
a       <- nrow(group_stats)
sigma_m <- sqrt(sum((group_stats$mean - mean(chapter_3_table_3$Rating))^2) / a)
sigma_m
HideShow
[1] 1.247219
HideShow
f_base <- sigma_m / sqrt(ms_w)
f_base
HideShow
[1] 1.270978
HideShow
# Squaring f gives the signal-to-noise ratio itself.
f_base^2
HideShow
[1] 1.615385
The same signal-to-noise measures in DMAR

The same group summaries give Cohen’s ff in DMAR. The observed FF statistic also gives confidence intervals for ff and for its square.

HideShow
F_value <- 24.23
df_1    <- 2    # numerator df
df_2    <- 27   # denominator df
N       <- 30

# Cohen's f (the square root of the signal-to-noise ratio):
cohen_f(means = group_stats$mean, var_within = ms_w,
        n_per_group = group_stats$n)
term value
cohen_f 1.271
HideShow
#> 1.271 — the f_base computed by hand above

# A confidence interval on Cohen's f from the observed F statistic:
ci_srsnr(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
         conf_level = 0.95)
term value
ci_lower 0.754
ci_upper 1.746

Confidence level: 95%

HideShow
#> [0.754, 1.746] — matches book p. 116.
ci_snr(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
       conf_level = 0.95)
term value
ci_lower 0.568
ci_upper 3.049

Confidence level: 95%

HideShow
# Equivalently, using the design-stage entry to ci_srsnr() that takes
# means + within-group variance + n directly, no F-value required:
ci_srsnr(means       = group_stats$mean,
         var_within  = ms_w,
         n_per_group = group_stats$n,
         conf_level  = 0.95)
term value
ci_lower 0.754
ci_upper 1.746

Confidence level: 95%

The median-unbiased estimate of ff uses the value of the noncentrality parameter for which the observed FF is the median (book p. 116).

HideShow
median_f <- function(F_value, df_1, df_2, N) {
  if (pf(F_value, df_1, df_2) <= 0.5) return(0)
  lambda <- uniroot(
    function(lambda) pf(F_value, df_1, df_2, ncp = lambda) - 0.5,
    interval = c(0, N), extendInt = "downX"
  )$root
  sqrt(lambda / N)
}
median_f(F_value, df_1, df_2, N)
HideShow
[1] 1.243929
HideShow
#> 1.244 — matches book p. 116.

3.9.2 — Measures of Association Strength

Computing R2R^2 and ω2\omega^2

One of the advantages of an object oriented language, such as R, is that objects can contain other objects and these objects can be used within other functions. Below we perform an anova using the aov() function and then ask R to state the various objects that are available using the names() function.

HideShow
Result <- aov(Rating ~ as.factor(Condition), data=chapter_3_table_3)
Summary_Output <- summary(Result)

#View the structure of what is in the Summary_Output object.
str(Summary_Output)
HideShow
List of 1
 $ :Classes 'anova' and 'data.frame':   2 obs. of  5 variables:
  ..$ Df     : num [1:2] 2 27
  ..$ Sum Sq : num [1:2] 46.7 26
  ..$ Mean Sq: num [1:2] 23.333 0.963
  ..$ F value: num [1:2] 24.2 NA
  ..$ Pr(>F) : num [1:2] 9.42e-07 NA
 - attr(*, "class")= chr [1:2] "summary.aov" "listof"
HideShow
# Extract the various attributes of interest (first using double square brackets).
Summary_Output[[1]]["Df"]
HideShow
                     Df
as.factor(Condition)  2
Residuals            27
HideShow
Summary_Output[[1]]["Mean Sq"]
HideShow
                     Mean Sq
as.factor(Condition)  23.333
Residuals              0.963
HideShow
Summary_Output[[1]]["Sum Sq"]
HideShow
                     Sum Sq
as.factor(Condition) 46.667
Residuals            26.000
HideShow
Summary_Output[[1]]["F value"]
HideShow
                     F value
as.factor(Condition)  24.231
Residuals                   
HideShow
Summary_Output[[1]]["Pr(>F)"]
HideShow
                        Pr(>F)    
as.factor(Condition) 9.421e-07 ***
Residuals                         
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
HideShow
#Further, objects within the above objects can themselves be extracted:
Summary_Output[[1]]["Df"][1,1]
HideShow
[1] 2
HideShow
Summary_Output[[1]]["Df"][2,1]
HideShow
[1] 27
HideShow
Summary_Output[[1]]["Mean Sq"][1,1]
HideShow
[1] 23.33333
HideShow
Summary_Output[[1]]["Mean Sq"][2,1]
HideShow
[1] 0.962963

Given the above information, Omega^2 can be obtained by extracting the necessary objects.

HideShow
SS_B <- Summary_Output[[1]]["Sum Sq"][1,1]
SS_W <- Summary_Output[[1]]["Sum Sq"][2,1]
df_1 <- Summary_Output[[1]]["Df"][1,1]
df_2 <- Summary_Output[[1]]["Df"][2,1]
MS_W <- Summary_Output[[1]]["Mean Sq"][2,1]

SS_T <- SS_B + SS_W

(Omega_Sq <- (SS_B-df_1*MS_W)/(SS_T + MS_W))
HideShow
[1] 0.6076459
HideShow
#> 0.608 — matches book p. 118

#Or, using F as follows:
F_Val <- Summary_Output[[1]]["F value"][1,1]
df_2 <- Summary_Output[[1]]["Df"][2,1]

(df_1*(F_Val-1))/(df_1*(F_Val-1)+(df_1+df_2+1))
HideShow
[1] 0.6076459
HideShow
#> 0.608 — matches book p. 118 (Equation 3.98)

Similarly, for R^2

HideShow
E_R <- SS_T
E_F <- SS_W
(R2 <- (E_R - E_F)/E_R)
HideShow
[1] 0.6422018
HideShow
#> 0.642 — matches book p. 118

Or for Adjusted R^2

HideShow
N <- df_1 + df_2 + 1
a <- df_1+1

1 - ((N-1)/(N-a))*(1-R2)
HideShow
[1] 0.6156983
HideShow
#> 0.616 — matches book p. 118 (Equation 3.99)

3.9.2.1 — Confidence Intervals for Measures of Association Strength

The preceding calculations give sample R2R^2 and ω̂2\hat\omega^2. DMAR also inverts the noncentral FF distribution for confidence limits on the population proportion of variance accounted for.

HideShow
F_value <- 24.23
df_1    <- 2    # numerator df
df_2    <- 27   # denominator df
N       <- 30

# Omega-squared with a noncentral-F CI. For a one-way design the "partial" and
# "total" omega-squared coincide, which is the estimand asked for here; F and
# its degrees of freedom alone cannot identify a total in a larger design.
ci_omega_squared(F_value = F_value, df_effect = df_1, df_error = df_2, N = N,
                 conf_level = 0.95, estimand = "partial")
effect omega_squared_partial omega_squared_partial_ci_lower omega_squared_partial_ci_upper F_value df_effect df_error N
overall 0.608 0.362 0.753 24.230 2 27 30

Confidence level: 95%

HideShow
#> 0.608 — the Omega_Sq computed by hand above (book p. 118)
#> 0.362, 0.753 — matches book p. 119

# Asymptotic variance of omega-squared (Fleishman 1980), useful for
# Wald-style CIs or meta-analytic weighting. This one has no base-R
# counterpart; we feed it the hand-computed estimate from above.
var_omega_squared(true_omega_squared = Omega_Sq,
                  df_effect = df_1, df_error = df_2, N = N)
term value
var_omega_squared 0.011
HideShow
# Proportion of variance accounted for, with a noncentral-F CI:
ci_pvaf(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
        conf_level = 0.95)
term value prob_less prob_greater
ci_lower 0.362 0.025 0.975
pvaf 0.642 NA NA
ci_upper 0.753 0.975 0.025
actual_coverage 0.950 NA NA

Confidence level: 95%

HideShow
#> 0.362, 0.753 — matches book p. 119;
#> pvaf = 0.642 is the R^2 computed by hand above (book p. 118)

# A 90% (1 - 2*alpha) interval is often reported for variance-accounted-for
# measures, the interest being a lower bound on a non-negative quantity:
ci_pvaf(F_value = F_value, df_1 = df_1, df_2 = df_2, N = N,
        conf_level = 0.90)
term value prob_less prob_greater
ci_lower 0.409 0.050 0.950
pvaf 0.642 NA NA
ci_upper 0.735 0.950 0.050
actual_coverage 0.900 NA NA

Confidence level: 90%

3.9.4 — Alternative Representations of Effects

3.9.4.1 — Binomial Effect Size Display (BESD)

A binomial effect size display (using the example from Rosenthal and Rubin (1982)).

HideShow
# Taken from Table 3.6
r <- .32
rbind(c(.5 + r/2, .5 - r/2)*100,
      c(.5 - r/2, .5 + r/2)*100)
HideShow
     [,1] [,2]
[1,]   66   34
[2,]   34   66

3.9.4.2 — Common Language (CL) Effect Size

Common language (CL) effect size. Recalling the example above where we have two groups (taken from Table 3 in Chapter 3). We repeat the data here. We then use the expand.grid() function (as used in the Chapter 1 R code) in order to find all possible pairings of the scores.

HideShow
group_1 <- c(6, 5, 4, 7, 7, 5, 5, 7, 7, 7)
group_2 <- c(5, 4, 4, 3, 4, 3, 4, 4, 4, 5)

Grid <- expand.grid(group_1=group_1, group_2=group_2)
Difs <- Grid[,1] - Grid[,2]

# Note that this is not corrected for ties.
(CL_Uncorrected <- mean(Difs > 0))
HideShow
[1] 0.86
HideShow
# Proportion of ties
(Ties <- mean(Difs==0))
HideShow
[1] 0.12
HideShow
(CL.Corrected <- CL_Uncorrected + .5*Ties)
HideShow
[1] 0.92
Cliff’s measure
HideShow
# Note that `Difs` is defined above.
mean(Difs > 0) - mean(Difs <0)
HideShow
[1] 0.84

3.10 — Statistical Assumptions

3.10.3 — Checking for Normality and Homogeneity of Variance

Sections 3.10.3 and 3.10.4 use the drinking data of Table 3.7: the average number of standard drinks per week reported by homeless alcoholics (Smith et al., 1998) at the 9-month follow-up, across five therapy groups. We load it before using it.

HideShow
data(chapter_3_table_7_raw)
O’Brien’s test

Here we compute O’Brien’s test step-by-step.

HideShow
Y_i1 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==1,"Drinks"]
Ybar_1 <- mean(Y_i1)
s2_1 <- var(Y_i1)
n_1 <- length(Y_i1)

Y_i2 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==2,"Drinks"]
Ybar_2 <- mean(Y_i2)
s2_2 <- var(Y_i2)
n_2 <- length(Y_i2)


Y_i3 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==3,"Drinks"]
Ybar_3 <- mean(Y_i3)
s2_3 <- var(Y_i3)
n_3 <- length(Y_i3)

Y_i4 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==4,"Drinks"]
Ybar_4 <- mean(Y_i4)
s2_4 <- var(Y_i4)
n_4 <- length(Y_i4)

Y_i5 <- chapter_3_table_7_raw[chapter_3_table_7_raw$Group==5,"Drinks"]
Ybar_5 <- mean(Y_i5)
s2_5 <- var(Y_i5)
n_5 <- length(Y_i5)

r_1 <- (((n_1-1.5)*n_1*((Y_i1-Ybar_1)^2))-(.5*s2_1*(n_1-1)))/((n_1-1)*(n_1-2))
r_2 <- (((n_2-1.5)*n_2*((Y_i2-Ybar_2)^2))-(.5*s2_2*(n_2-1)))/((n_2-1)*(n_2-2))
r_3 <- (((n_3-1.5)*n_3*((Y_i3-Ybar_3)^2))-(.5*s2_3*(n_3-1)))/((n_3-1)*(n_3-2))
r_4 <- (((n_4-1.5)*n_4*((Y_i4-Ybar_4)^2))-(.5*s2_4*(n_4-1)))/((n_4-1)*(n_4-2))
r_5 <- (((n_5-1.5)*n_5*((Y_i5-Ybar_5)^2))-(.5*s2_5*(n_5-1)))/((n_5-1)*(n_5-2))

# Notice the following, where the first column is the mean of the r.j and the second
#column is the variance.
as.matrix(rbind(
c(mean(r_1), s2_1),
c(mean(r_2), s2_2),
c(mean(r_3), s2_3),
c(mean(r_4), s2_4),
c(mean(r_5), s2_5)))
HideShow
          [,1]      [,2]
[1,]  2439.836  2439.836
[2,]  3713.122  3713.122
[3,] 22162.041 22162.041
[4,]  3952.290  3952.290
[5,]  2008.812  2008.812
HideShow
# Add a column of the r values.
chapter_3_table_7_raw$r <- c(r_1, r_2, r_3, r_4, r_5)

Now, using the new column of data in the data set, r, we perform the ANOVA as before.

HideShow
summary(aov(r ~ as.factor(Group), data=chapter_3_table_7_raw))
HideShow
                 Df    Sum Sq   Mean Sq F value Pr(>F)
as.factor(Group)  4 5.074e+09 1.269e+09   0.953  0.438
Residuals        83 1.105e+11 1.331e+09               
Levene’s test

The Levene test is implemented in the car package with the LeveneTest() function. Note that below we use center=mean, though the default is center=median.

HideShow
leveneTest(Drinks ~ as.factor(Group), data=chapter_3_table_7_raw, center=mean)
HideShow
Levene's Test for Homogeneity of Variance (center = mean)
      Df F value Pr(>F)
group  4  1.7558 0.1456
      83               
Visualizing distribution shape

Here we plot a quantile-quantile plot of the chapter_3_table_7_raw data, ignoring groups. In ggplot2 the sample is mapped to the sample aesthetic, and stat_qq() draws the points against theoretical normal quantiles while stat_qq_line() adds the reference line a normal sample would follow. Points bending away from that line indicate a departure from normality.

HideShow
ggplot(chapter_3_table_7_raw, aes(sample = Drinks)) +
  stat_qq(size = 1.6, alpha = 0.8) +
  stat_qq_line(color = "#0C2340", linewidth = 0.8) +
  labs(x = "Theoretical quantiles", y = "Sample quantiles")

Figure 3.3. Distribution of standard drinks per week

The intake measurements in Smith et al. (1998) have a long right tail. The bars below use the grouped frequencies read from the published histogram. The normal curve uses the intake mean and standard deviation printed in the original figure.

HideShow
bin_width <- 25
intake <- data.frame(
  center = seq(0, 575, by = bin_width),
  frequency = c(11, 11, 11, 11, 8, 9, 7, 4, 4, 5, 6, 2,
                 6,  2,  1,  0, 1, 1, 2, 2, 0, 0, 1, 1)
)

# Convert the normal density to the same frequency scale as the bars.
intake_mean <- 149.7
intake_sd <- 133.43
edges <- range(intake$center) + c(-0.5, 0.5) * bin_width
curve_x <- seq(edges[1], edges[2], length.out = 500)
normal_curve <- data.frame(
  x = curve_x,
  frequency = dnorm(curve_x, intake_mean, intake_sd) *
    sum(intake$frequency) * bin_width
)

ggplot(intake, aes(center, frequency)) +
  geom_col(width = bin_width, fill = "grey74", colour = "grey25", linewidth = 0.4) +
  geom_line(data = normal_curve, aes(x = x), colour = "#0C2340", linewidth = 0.85) +
  annotate("text", x = 570, y = 11.5, label = "bar(italic(Y)) == 149.7",
           parse = TRUE, hjust = 1) +
  annotate("text", x = 570, y = 10.7, label = "italic(s)[italic(Y)] == 133.43",
           parse = TRUE, hjust = 1) +
  scale_x_continuous(breaks = seq(0, 550, by = 50), expand = expansion(0)) +
  scale_y_continuous(breaks = seq(0, 12, by = 2), expand = expansion(0)) +
  coord_cartesian(xlim = edges, ylim = c(0, 12)) +
  labs(x = "Average number of standard drinks per week", y = "Frequency")
Histogram of weekly drinking at intake. The four leftmost bars are tallest, and a sparse right tail extends beyond 500 drinks per week. A fitted normal curve is overlaid.

Figure 3.3. Average number of standard drinks per week at intake (Smith et al., 1998).

For the remaining examples, we return to the individual nine-month follow-up measurements in chapter_3_table_7_raw. The moments package reports raw kurtosis (3 for a normal distribution). The DMAR summaries below use a small-sample correction and report excess kurtosis (0 for a normal distribution).

HideShow
moments::skewness(chapter_3_table_7_raw$Drinks)
HideShow
[1] 4.770605
HideShow
moments::kurtosis(chapter_3_table_7_raw$Drinks)
HideShow
[1] 32.00413
Visualizing confidence intervals

Beyond distributional shape, we can visualize group means and variability using confidence intervals. These plots also help in assessing potential assumption violations.

Here we visualize the confidence interval limits by group. We use the t.test() function as before, but not literally for the hypothesis test. Recall that this function also provides a confidence interval for the population mean. We extract the conf.int results from the t.test() of each group and plot one interval per group.

HideShow
# Give the five nine-month follow-up groups the labels used in Figures 3.4 and 3.5.
drinks <- chapter_3_table_7_raw |>
  mutate(Therapy = factor(Group, levels = 1:5,
    labels = c("T1 CRA-D", "T1 CRA+D", "T1 Std", "T2 CRA-D", "T2 Std")))
Group_Names <- levels(drinks$Therapy)
Group_Names
HideShow
[1] "T1 CRA-D" "T1 CRA+D" "T1 Std"   "T2 CRA-D" "T2 Std"  
Figure 3.4. Confidence intervals around group means of drinks per week

Beyond a single distribution, plotting a confidence interval for each group’s mean makes between-group differences and unequal spread visible at once. This figure shows the 95% confidence interval around the mean number of drinks per week for each of the five therapy groups at the 9-month follow-up (Smith et al., 1998), each computed from that group’s own standard deviation. The widely differing interval lengths are the figure’s lesson: with roughly equal group sizes, intervals that differ several-fold in width signal a likely violation of homogeneity of variance.

HideShow
# One 95% CI per group, from each group's own t.test (separate-variances limits).
ci_by_group <- function(data, value) {
  data |>
    group_by(Therapy) |>
    summarize(mean = mean(.data[[value]]),
              lower = t.test(.data[[value]])$conf.int[1],
              upper = t.test(.data[[value]])$conf.int[2],
              .groups = "drop")
}
ci_drinks <- ci_by_group(drinks, "Drinks")

ggplot(ci_drinks, aes(Therapy, mean)) +
  geom_hline(yintercept = 0, color = "grey70", linewidth = 0.3) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.18,
                color = "black", linewidth = 0.8) +
  geom_point(size = 2.6, shape = 22, fill = "#0C2340",
             color = "black") +
  labs(x = "Therapy group", y = "95% CI for number of drinks")
Figure 3.4. Confidence intervals around means for number of drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

Figure 3.4. Confidence intervals around means for number of drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

The T1 Std interval is several times longer than the others even though its sample size is comparable, the hallmark of heterogeneous variances that Section 3.10 warns against.

Skewness and kurtosis

To complement the visual diagnostics, we calculate descriptive statistics, including skewness and kurtosis, which provide numeric summaries of distributional shape.

The psych package has a nice descriptive statistics function, describe() that can easily be applied to a data set. To obtain a useful set of descriptives for all variables in a data set, describe() can be used as follows.

HideShow
describe(chapter_3_table_7_raw)
HideShow
         vars  n    mean       sd median trimmed    mad     min       max
Group       1 88    3.09     1.42   3.00    3.11   1.48    1.00      5.00
Drinks      2 88   36.88    81.96   3.85   19.64   5.70    0.00    624.62
LgDrinks    3 88    0.84     0.85   0.68    0.77   1.01    0.00      2.80
r           4 88 6718.94 36447.29 649.23 1217.95 595.96 -106.15 335136.99
             range  skew kurtosis      se
Group         4.00 -0.04    -1.35    0.15
Drinks      624.62  4.69    28.28    8.74
LgDrinks      2.80  0.40    -1.34    0.09
r        335243.14  8.37    71.99 3885.29

For the follow-up sample, compare the raw kurtosis from moments with the three definitions of excess kurtosis available in psych::describe(). Its type 1 estimate is the raw kurtosis minus 3. Types 2 and 3 use different sample-size adjustments.

HideShow
kurtosis(chapter_3_table_7_raw$Drinks)
HideShow
[1] 32.00413
HideShow
describe(chapter_3_table_7_raw$Drinks, type=1)$kurtosis
HideShow
[1] 29.00413
HideShow
describe(chapter_3_table_7_raw$Drinks, type=2)$kurtosis
HideShow
[1] 30.79357
HideShow
describe(chapter_3_table_7_raw$Drinks, type=3)$kurtosis
HideShow
[1] 28.2809

The book uses what describe() calls type=2. Thus, to reproduce the values in the descriptive statistics table, we have the code below that also adds the group name to the output.

HideShow
rbind(c(Group=Group_Names[1],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==1,"Drinks"], type=2)),
      c(Group=Group_Names[2],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==2,"Drinks"], type=2)),
      c(Group=Group_Names[3],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==3,"Drinks"], type=2)),
      c(Group=Group_Names[4],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==4,"Drinks"], type=2)),
      c(Group=Group_Names[5],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==5,"Drinks"], type=2)))
HideShow
     Group      vars n  mean     sd       median   trimmed  mad      min
[1,] "T1 CRA-D" 1    15 33.80431 49.3947  10.97846 25.98249 16.27667 0  
[2,] "T1 CRA+D" 1    19 26.4196  60.93539 0        15.57014 0        0  
[3,] "T1 Std"   1    17 71.51416 148.8692 28.8     39.40836 40.91976 0  
[4,] "T2 CRA-D" 1    17 20.31077 62.86724 0        5.864205 0        0  
[5,] "T2 Std"   1    20 33.76562 44.81977 13.47692 25.65317 19.98089 0  
     max      range    skew     kurtosis se      
[1,] 169.2923 169.2923 1.836401 3.100115 12.75366
[2,] 237.28   237.28   2.782492 8.104232 13.97954
[3,] 624.6154 624.6154 3.587491 13.73201 36.10609
[4,] 257.32   257.32   3.778988 14.76502 15.24755
[5,] 164.0615 164.0615 1.634646 2.432478 10.02201
The same descriptives in DMAR

DMAR’s descriptives() returns a tidy descriptive-statistics table, including DMAR’s skewness and kurtosis, for one or more variables. Below we apply it to the Drinks and LgDrinks variables, and then build a by-group summary that places the raw and log skewness side by side, which makes §3.10.4’s argument for the log transformation visible at a glance.

HideShow
descriptives(chapter_3_table_7_raw[, c("Drinks", "LgDrinks")])$descriptives
HideShow
  variable    type  n n_missing prop_missing      mean    median         sd min
1   Drinks numeric 88         0            0 36.879240 3.8461539 81.9633081   0
2 LgDrinks numeric 88         0            0  0.840819 0.6834186  0.8505308   0
         max q25       q75  skewness  kurtosis
1 624.615385   0 36.433846 4.8537336 30.793569
2   2.796307   0  1.572357 0.4178558 -1.308316
HideShow
chapter_3_table_7_raw %>%
  group_by(Group) %>%
  summarize(
    n         = n(),
    mean_d    = mean(Drinks),    sd_d    = sd(Drinks),
    skew_d    = DMAR::skewness(Drinks),
    mean_lg   = mean(LgDrinks),  sd_lg   = sd(LgDrinks),
    skew_lg   = DMAR::skewness(LgDrinks),
    .groups   = "drop"
  )
HideShow
# A tibble: 5 × 8
  Group     n mean_d  sd_d skew_d mean_lg sd_lg skew_lg
  <int> <int>  <dbl> <dbl>  <dbl>   <dbl> <dbl>   <dbl>
1     1    15   33.8  49.4   1.84   1.01  0.803 -0.0322
2     2    19   26.4  60.9   2.78   0.540 0.827  1.37  
3     3    17   71.5 149.    3.59   1.23  0.869 -0.237 
4     4    17   20.3  62.9   3.78   0.391 0.744  1.94  
5     5    20   33.8  44.8   1.63   1.05  0.781 -0.209 

Note the dramatic drop in skewness from the raw to the log scale, exactly §3.10.4’s argument for the transformation.

3.10.4 — Transformations

If assumptions appear violated, transformations such as the logarithm or square root may stabilize variance and normalize distributions, which we can evaluate using the same descriptive and visual methods.

Using now the log of the number of Drinks, we can use the describe() function as follows, where we replace Drinks with LgDrinks (note that LgDrinks is already in the data set).

HideShow
rbind(c(Group=Group_Names[1],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==1,"LgDrinks"], type=2)),
      c(Group=Group_Names[2],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==2,"LgDrinks"], type=2)),
      c(Group=Group_Names[3],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==3,"LgDrinks"], type=2)),
      c(Group=Group_Names[4],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==4,"LgDrinks"], type=2)),
      c(Group=Group_Names[5],
        describe(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==5,"LgDrinks"], type=2)))
HideShow
     Group      vars n  mean      sd        median   trimmed   mad       min
[1,] "T1 CRA-D" 1    15 1.007188  0.8033638 1.078401 0.9905094 1.147596  0  
[2,] "T1 CRA+D" 1    19 0.5400679 0.8274548 0        0.4637766 0         0  
[3,] "T1 Std"   1    17 1.228967  0.8689398 1.474216 1.206408  0.8106354 0  
[4,] "T2 CRA-D" 1    17 0.3912861 0.7442338 0        0.282647  0         0  
[5,] "T2 Std"   1    20 1.053933  0.7811781 1.150223 1.05333   1.063293  0  
     max      range    skew        kurtosis   se       
[1,] 2.231195 2.231195 -0.03217937 -1.457266  0.2074276
[2,] 2.377088 2.377088 1.373427    0.3182206  0.1898312
[3,] 2.796307 2.796307 -0.2371426  -0.8679882 0.2107489
[4,] 2.412158 2.412158 1.943825    2.782116   0.1805032
[5,] 2.217646 2.217646 -0.2085922  -1.387944  0.1746767

Note that, had we been interested in applying a different type of transformation to the data, that can be done directly within the describe() function on the data of interest, such as what we do below using the sqrt() function (for the square root transformation).

HideShow
rbind(c(Group=Group_Names[1],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==1,"Drinks"]), type=2)),
      c(Group=Group_Names[2],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==2,"Drinks"]), type=2)),
      c(Group=Group_Names[3],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==3,"Drinks"]), type=2)),
      c(Group=Group_Names[4],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==4,"Drinks"]), type=2)),
      c(Group=Group_Names[5],
        describe(sqrt(chapter_3_table_7_raw[chapter_3_table_7_raw$Group ==5,"Drinks"]), type=2)))
HideShow
     Group      vars n  mean     sd       median   trimmed  mad      min
[1,] "T1 CRA-D" 1    15 4.229386 4.129589 3.313376 3.879196 4.912411 0  
[2,] "T1 CRA+D" 1    19 2.596713 4.557393 0        1.996097 0        0  
[3,] "T1 Std"   1    17 5.937236 6.207242 5.366563 5.062714 6.33236  0  
[4,] "T2 CRA-D" 1    17 1.886724 4.218765 0        1.068875 0        0  
[5,] "T2 Std"   1    20 4.374796 3.923851 3.645773 4.040459 5.317046 0  
     max      range    skew      kurtosis   se       
[1,] 13.01124 13.01124 0.8036426 -0.2710347 1.066255 
[2,] 15.4039  15.4039  1.873749  2.622742   1.045538 
[3,] 24.99231 24.99231 1.877095  4.900944   1.505477 
[4,] 16.0412  16.0412  2.810644  8.264705   1.023201 
[5,] 12.80865 12.80865 0.5849369 -0.6513498 0.8773998

Using the descriptive statistics previously calculated on the number of Drinks by group, here we fit a regression model with the log standard deviations conditional on the log of the means for the five groups. First, we create a data frame of the log transformed means and standard deviations. Then, we use the lm() function to fit a linear model, here a simple regression model.

HideShow
Log_Descriptives <- data.frame(LogMeans=log(c(Ybar_1, Ybar_2, Ybar_3, Ybar_4, Ybar_5)),
                               LogSD=log(sqrt(c(s2_1, s2_2, s2_3, s2_4, s2_5))))
summary(lm(LogSD~LogMeans, data=Log_Descriptives))
HideShow

Call:
lm(formula = LogSD ~ LogMeans, data = Log_Descriptives)

Residuals:
      1       2       3       4       5 
-0.2926  0.1003  0.2545  0.3267 -0.3889 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   1.5795     1.4096   1.121    0.344
LogMeans      0.7422     0.3977   1.866    0.159

Residual standard error: 0.3735 on 3 degrees of freedom
Multiple R-squared:  0.5372,    Adjusted R-squared:  0.3829 
F-statistic: 3.482 on 1 and 3 DF,  p-value: 0.1589
Figure 3.5. Confidence intervals around the mean of log drinks per week

The natural remedy for the skew and unequal spread in Figure 3.4 is a transformation. This figure repeats the five-group confidence-interval plot on the log-transformed number of drinks per week (variable LgDrinks) at the 9-month follow-up. On the log scale the interval lengths are far more uniform, showing that the transformation has largely stabilized the variance across groups, the payoff Section 3.10 describes.

HideShow
ci_logdrinks <- ci_by_group(drinks, "LgDrinks")

ggplot(ci_logdrinks, aes(Therapy, mean)) +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.18,
                color = "black", linewidth = 0.8) +
  geom_point(size = 2.6, shape = 22, fill = "#0C2340",
             color = "black") +
  labs(x = "Therapy group", y = "95% CI for log number of drinks")
Figure 3.5. Confidence intervals around the mean of log-transformed drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

Figure 3.5. Confidence intervals around the mean of log-transformed drinks per week for five groups at 9-month follow-up (Smith et al., 1998).

With the data on the log scale the five intervals are of comparable length, in sharp contrast to Figure 3.4, illustrating how a log transformation can bring badly skewed, heteroscedastic data closer to the assumptions of the one-way model.

ANOVA on log transformed number of Drinks

HideShow
summary(aov(LgDrinks ~ as.factor(Group), data=chapter_3_table_7_raw))
HideShow
                 Df Sum Sq Mean Sq F value Pr(>F)  
as.factor(Group)  4   9.04  2.2597    3.48 0.0112 *
Residuals        83  53.90  0.6494                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

3.11 — Power of the FF Test: One-Way ANOVA

3.11.1 — Determining an Appropriate Sample Size

Power computed directly from the noncentral FF distribution

Computing the supposed noncentral FF parameter based on a set of supposed population means (for a hypothetical situation)

HideShow
Supposed_Within_Group_SD <- 100
Supposed_Group_Means <- c(400, 450, 500)
Grand_Mean <- mean(Supposed_Group_Means)
Treatment_Effects <- Supposed_Group_Means-Grand_Mean
n <- 10
a <- 3
N <- n*a
(lambda <- 10*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 5
HideShow
(f2 <- lambda/N)
HideShow
[1] 0.1666667
HideShow
(f <- sqrt(f2))
HideShow
[1] 0.4082483

Using the above supposed scores, the ff effect size can be estimated as follows, with
(length(Supposed.Group.Means)-1)/length(Supposed.Group.Means)
being used in order to use nn in the denominator of the variance, rather than the default or typical denominator (n−1n-1).

HideShow
sigma_m <- sqrt(var(Supposed_Group_Means)*(length(Supposed_Group_Means)-1)/length(Supposed_Group_Means))
f <- sigma_m/Supposed_Within_Group_SD
f
HideShow
[1] 0.4082483

In R, we can find the exact power based on the area of the particular noncentral FF-distribution for the specified degrees of freedom by determining the area that is beyond the critical value from the central FF-distributoin as follows, for different sample sizes (some of this is calculated above but it is repeated here for completeness).

HideShow
# Constant (parameters)
(Supposed_sigma_e <- 100)
HideShow
[1] 100
HideShow
(Supposed_Group_Means <- c(400, 450, 500))
HideShow
[1] 400 450 500
HideShow
(a <- length(Supposed_Group_Means))
HideShow
[1] 3
HideShow
(Grand_Mean <- mean(Supposed_Group_Means))
HideShow
[1] 450
HideShow
(alpha <- Supposed_Group_Means-Grand_Mean)
HideShow
[1] -50   0  50
HideShow
(Supposed_sigma_m <- sqrt(sum(alpha^2)/a))
HideShow
[1] 40.82483
HideShow
(f <- Supposed_sigma_m/Supposed_sigma_e)
HideShow
[1] 0.4082483
HideShow
# Variables
(n <- 10)
HideShow
[1] 10
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 5
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.354131
HideShow
# Statistical power.
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.4579923

Here we use the above Constant values but specify a different sample size (and then a new lambda results)

HideShow
# Variables
(n <- 25)
HideShow
[1] 25
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 12.5
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.123907
HideShow
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.8827749

Here we use the above Constant values but specify a different sample size (and then a new lambda results)

HideShow
# Variables
(n <- 20)
HideShow
[1] 20
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 10
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.158843
HideShow
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.7933118

Trying to hone in on power of .80, we try n=21, which is the smallest sample size that satisfies desired power.

HideShow
# Variables
(n <- 21)
HideShow
[1] 21
HideShow
# Constant Conditional on the situation (i.e., Conditional based on n)
(lambda <- n*sum(Treatment_Effects^2)/Supposed_Within_Group_SD^2)
HideShow
[1] 10.5
HideShow
(CV <- qf(.95, df1=a-1, df2=a*n-a))
HideShow
[1] 3.150411
HideShow
(power <- pf(CV, df1=a-1, df2=a*n-a, ncp=lambda, lower.tail=FALSE))
HideShow
[1] 0.8147697
Power analysis with the pwr package

Rather than planning sample size as above based on the definitional forms and noncentral distributions directly, the pwr package (loaded with the other packages above) can be used as follows.

HideShow
# Returns exact power based on fractional sample sizes.
pwr.anova.test(k=3, f=f, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 3
              n = 20.30205
              f = 0.4082483
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
# Here we "round up" by using the ceiling function to get
# the necessary per-group sample size.
ceiling(pwr.anova.test(k=3, f=f, sig.level=.05, power=.80)$n)
HideShow
[1] 21

Using the Brown and Miller results, we can plan with the median-unbiased estimate of ff, or with a one-sided lower confidence bound (book p. 139).

HideShow
median_f(F_value = 6.612, df_1 = 1, df_2 = 24, N = 26)
HideShow
[1] 0.4988501
HideShow
ci_srsnr(F_value = 6.612, df_1 = 1, df_2 = 24, N = 26,
         alpha_lower = 0.20, alpha_upper = 0)
term value
ci_lower 0.323
ci_upper Inf

Confidence level: 80% (one-sided: the lower limit is the 80% lower confidence bound, with tail area 0.2 below it and none above the upper limit)

HideShow
ci_srsnr(F_value = 6.612, df_1 = 1, df_2 = 24, N = 26,
         alpha_lower = 0.3333, alpha_upper = 0)
term value
ci_lower 0.409
ci_upper Inf

Confidence level: 66.67% (one-sided: the lower limit is the 66.67% lower confidence bound, with tail area 0.3333 below it and none above the upper limit)

HideShow
#> About 0.499 for the median-unbiased estimate, with lower bounds of
#> 0.323 and 0.409 at 80% and 66.7% confidence, respectively.

# Using the book’s rounded median-unbiased estimate for planning:
pwr.anova.test(k=2, f=.4988, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 16.79008
              f = 0.4988
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
#> n = 16.79, so 17 per group (N = 34) — matches book p. 139

# Using the 80% single-sided confidence interval limits.
pwr.anova.test(k=2, f=.3230, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 38.60018
              f = 0.323
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
#> n = 38.60, so 39 per group — matches book p. 139

# Using the 66.66% single-sided confidence interval limits.
pwr.anova.test(k=2, f=.4088, sig.level=.05, power=.80)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 24.48155
              f = 0.4088
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
#> n = 24.48, so 25 per group — matches book p. 139

To evaluate power at a given sample size for supposed population value, we can also use the pwr.anova.test() function, but now specifying sample size instead of (desired) power. The 17 participants per group that the median effect size called for would, if the population effect were really the 80% lower limit of f=.3230f = .3230, deliver much less power than the .80 that was planned for.

HideShow
pwr.anova.test(k=2, n=17, f=.3230, sig.level=.05)
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 2
              n = 17
              f = 0.323
      sig.level = 0.05
          power = 0.4471123

NOTE: n is number in each group
HideShow
#> power = .447 — matches book p. 139
The same plan three ways: base R, pwr, and DMAR

Take a medium effect for three groups, Cohen’s f=0.25f = 0.25, and ask for 80% power at α=.05\alpha = .05. All three routes below are the same noncentral-FF calculation; they differ only in what they ask the computer to solve for, and in how they round to whole participants. Base R first, by stepping the total sample size until power reaches .80 exactly as earlier in this section.

HideShow
f <- 0.25
a <- 3

# Power at a given total N, straight from the noncentral F distribution.
power_at_N <- function(N_total) {
  pf(qf(.95, df1 = a - 1, df2 = N_total - a),
     df1 = a - 1, df2 = N_total - a,
     ncp = N_total * f^2, lower.tail = FALSE)
}
c(N_157 = power_at_N(157), N_158 = power_at_N(158))
HideShow
    N_157     N_158 
0.7994818 0.8021998 

So 158 in total is the smallest sample reaching .80. The pwr package solves the same equation for nn per group, which it reports as a fraction; rounding up to whole participants per group gives 53×3=15953 \times 3 = 159.

HideShow
pwr_plan <- pwr.anova.test(k = a, f = f, sig.level = .05, power = .80)
pwr_plan
HideShow

     Balanced one-way analysis of variance power calculation 

              k = 3
              n = 52.3966
              f = 0.25
      sig.level = 0.05
          power = 0.8

NOTE: n is number in each group
HideShow
ceiling(pwr_plan$n) * a
HideShow
[1] 159

DMAR’s planners address the same two questions from the regression side, which is what makes them useful when the effect is stated as a variance accounted for rather than as ff: power (the probability of rejecting at a chosen effect size) and AIPE, accuracy in parameter estimation (the precision of the estimate). ss_power_R2() searches on the total NN, so for a fixed-effects design it returns the 158 found by hand above. Because the §3.11 material is framed in terms of Cohen’s ff, we convert via R2=f2/(1+f2)R^2 = f^2 / (1 + f^2).

HideShow
# Cohen's f -> R^2 conversion: R^2 = f^2 / (1 + f^2)
eta2 <- f^2 / (1 + f^2)
eta2
HideShow
[1] 0.05882353
HideShow
# ss_power_R2 returns the necessary total N for the F test. The predictors in
# an experiment are fixed by design rather than sampled, hence
# random_predictors = FALSE.
ss_power_R2(true_R2 = eta2, p = 2,                      # df_1 = a - 1 = 2
            alpha_level = 0.05, desired_power = 0.80,
            random_predictors = FALSE)
term value
necessary_N 158
actual_power 0.802
noncentral_f_parm 9.875
true_f2 0.062
HideShow
#> 158 — the N found by hand above; pwr's 52.40 per group is the same
#> calculation rounded differently

For accuracy in parameter estimation, suppose the anticipated population R2R^2 is .10 and the target is an expected full width of .10 for a 95% confidence interval. Set method = "analytic" to reproduce the analytical sample-size calculation. The predictor assumptions distinguish the first two plans.

HideShow
ss_aipe_R2(true_R2 = 0.10, p = 2, width = 0.10, conf_level = 0.95,
           random_predictors = TRUE, method = "analytic")
term value
necessary_N 502

For this analytical plan, check the mean full interval width by simulation at the proposed N. See ?ss_aipe_R2.

Confidence level: 95%

HideShow
#> N = 502 for random predictors.
ss_aipe_R2(true_R2 = 0.10, p = 2, width = 0.10, conf_level = 0.95,
           random_predictors = FALSE, method = "analytic")
term value
necessary_N 471

For this analytical plan, check the mean full interval width by simulation at the proposed N. See ?ss_aipe_R2.

Confidence level: 95%

HideShow
#> N = 471 for fixed predictors.

For the one-way design, plan directly for the interval on ω2\omega^2 at the same confidence level and target full width.

HideShow
ss_aipe_omega_squared(true_omega_squared = 0.10, df_effect = 2,
                      width = 0.10, conf_level = 0.95)
term value
necessary_N 473
expected_width 0.100
true_omega_squared 0.100
df_effect 2
width 0.100
conf_level 0.950

Confidence level: 95%

HideShow
#> N = 473.

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 3: Introduction to Model Comparisons: One-Way Between-Subjects Designs (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