R Code and Instructions
On this page
- 3.5 — One-Group Situation
- 3.5.3 — Numerical Example
- 3.7 — The General Case of One-Way Designs
- 3.7.2 — Numerical Example
- 3.9 — Measures of Effect
- 3.9.1 — Measures of Effect Size
- 3.9.1.2 — Confidence Intervals
- 3.9.1.4 — The Standardized Difference Between Means
- 3.9.1.5 — Confidence Intervals for Standardized Differences Between Means
- 3.9.1.6 — Standardized Effects, the Signal-to-Noise Ratio, and Confidence Intervals for f
- 3.9.2 — Measures of Association Strength
- 3.9.2.1 — Confidence Intervals for Measures of Association Strength
- 3.9.4 — Alternative Representations of Effects
- 3.9.4.1 — Binomial Effect Size Display (BESD)
- 3.9.4.2 — Common Language (CL) Effect Size
- 3.10 — Statistical Assumptions
- 3.10.3 — Checking for Normality and Homogeneity of Variance
- 3.10.4 — Transformations
- 3.11 — Power of the F Test: One-Way ANOVA
- 3.11.1 — Determining an Appropriate Sample Size
- How to Cite This Page
- References
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 ICC3.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).
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
[1] 104HideShow
[1] 104HideShow
5% 25% 50% 75% 95%
97.5 102.5 104.0 107.0 109.5 HideShow
[1] 4.898979HideShow
[1] 6Let’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
Sum_Y n Sum_Squared_Errors
1 624 6 120The model comparison and the test
Here we find 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.)
ValuesHideShow
Error_F df_F Error_R df_R F
1 120 5 336 6 9HideShow
[1] 9Linear 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 ' ' 1The critical value from an -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
[1] 6.607891The -value from an -test can be found using the
pf() function, in which the observed -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 -value). For our
example:
HideShow
[1] 0.03009925HideShow
[1] 0.03009925The equivalent test
As noted in the text, a -test
can be done. In R, the t.test() function with the null
values to test of mu=98 specified can be used.
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 -tests, paired
samples -test, and
independent-samples -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.
Doing a -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
[1] 3The critical value or values from a -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
[1] 2.015048HideShow
[1] -2.570582 2.570582The -value from a -test can be found using the
pt() function, in which the observed -value and degrees of freedom are
supplied as arguments. For a two-sided -value, the pt() function
can be used generically as 2*(1-pt(abs(t), df)), where the
absolute value is used for the observed -value.
HideShow
[1] 0.03009925For a one-sided -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 -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
[1] 0.9849504HideShow
[1] 0.01504962Had 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 -value. Again, it is important that the
absolute value function (i.e., abs()) is not used for
single-sided tests.
HideShow
[1] 0.01504962HideShow
[1] 0.98495043.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
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 4To 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
'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
[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
[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.
Axis labels and a title are added with labs().
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.
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.
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 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
Min. 1st Qu. Median Mean 3rd Qu. Max.
4.0 5.0 6.5 6.0 7.0 7.0 HideShow
Min. 1st Qu. Median Mean 3rd Qu. Max.
3 4 4 4 4 5 HideShow
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 2.25 3.00 3.00 4.00 4.00 HideShow
[1] 1.154701HideShow
[1] 0.6666667HideShow
[1] 1.054093Computations 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
# 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 10HideShow
[1] 3HideShow
[1] 30HideShow
[1] 26HideShow
[1] 72.66667HideShow
[1] 46.66667HideShow
[1] 23.33333HideShow
[1] 0.962963HideShow
[1] 27HideShow
[1] 29HideShow
[1] 2HideShow
[1] 24.23077HideShow
[1] 24.23077HideShow
[1] 24.23077HideShow
[1] 3.354131HideShow
[1] 9.421379e-07As a direct check that these intermediate quantities match the book’s Table 3.4, we plug the numbers into the formula.
HideShow
E_F E_R_minus_E_F MS_Between MS_Within F
26.000000 46.666667 23.333333 0.962963 24.230769 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
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 ' ' 1Note 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
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 ' ' 1The 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 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 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 ' ' 1A 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.
| 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, ; unpleasant, ).
| 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, , , , , , and partial . (For a one-way design partial equals , the full model’s .)
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 η<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
[1] 98.85884HideShow
[1] 109.1412Recall 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
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
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
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
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
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 -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.
Another way to enter the data above is as follows.
Yet another way uses the rep() function, which
replicates a value the specified number of times.
Now that we have data from two independent groups, we can perform a two-group -test and obtain the confidence interval as follows. Note that this -test does not assume homogeneity of variance, which we show momentarily.
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 -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
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 -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
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 -test as
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 , or by the control standard deviation for (book p. 111).
HideShow
d d_C
1.008572 0.807619 For Equation 3.86, DMAR applies the small-sample correction using the degrees of freedom for the chosen standardizer.
| term | value |
|---|---|
| smd | 0.977 |
| term | value |
|---|---|
| smd_c | 0.756 |
3.9.1.5 — Confidence Intervals for Standardized Differences Between Means
DMAR inverts the noncentral 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.
| term | value |
|---|---|
| ci_lower | 0.180 |
| smd | 1.009 |
| ci_upper | 1.819 |
Confidence level: 95%
| term | value |
|---|---|
| ci_lower | -0.039 |
| smd_c | 0.808 |
| ci_upper | 1.626 |
Confidence level: 95%
Figure 3.2. Noncentral distributions at the confidence limits
Section 3.9 forms a confidence interval for a standardized mean difference by inverting the noncentral- distribution. Using the Brown and Miller (1993) two-group example (, observed ), the limits of the 95% confidence interval for the noncentrality parameter are the two values whose noncentral- distributions place the observed at their 2.5th and 97.5th percentiles. The upper axis expresses each possible as a sample standardized mean difference . The same conversion takes the confidence limits for to limits for the population effect .
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 distributions at the limits of a 95% confidence interval for the noncentrality parameter (Brown & Miller, 1993).
On the lower distribution the observed sits at the 97.5th percentile and on the upper distribution at the 2.5th percentile; rescaled to 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 , whereas a two-group 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_pooledHideShow
[1] 0.9813068HideShow
[1] 3.057148The contrast itself is an ordinary two-group test, which base R performs with
t.test(). Pooling only the two groups being compared,
Cohen’s is the observed rescaled by the group sizes, .
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
[1] 6.067799HideShow
[1] 2.713602DMAR can recover the two-group estimate directly from the scores and give a 95% confidence interval for the corresponding population effect.
| term | value |
|---|---|
| smd | 2.714 |
| term | value |
|---|---|
| ci_lower | 1.453 |
| smd | 2.714 |
| ci_upper | 3.936 |
Confidence level: 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
[1] 0.9966722HideShow
[1] 0.9724956HideShow
[1] 1.058211| 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%
| 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%
| 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%
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 under that assumption.
HideShow
[1] 0.4045455HideShow
[1] 0.9577465| term | value |
|---|---|
| var_smd_exact | 0.480 |
| var_smd_approx | 0.405 |
| 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
Cohen’s by hand
The interval above is for the square root of the signal-to-noise ratio, which is Cohen’s . The point estimate needs no package at all: is the standard deviation of the group means, taking rather than as the denominator, divided by the within-group standard deviation .
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
[1] 0.962963HideShow
[1] 1.247219HideShow
[1] 1.270978HideShow
[1] 1.615385The same signal-to-noise measures in DMAR
The same group summaries give Cohen’s in DMAR. The observed statistic also gives confidence intervals for and for its square.
| term | value |
|---|---|
| cohen_f | 1.271 |
| term | value |
|---|---|
| ci_lower | 0.754 |
| ci_upper | 1.746 |
Confidence level: 95%
| term | value |
|---|---|
| ci_lower | 0.568 |
| ci_upper | 3.049 |
Confidence level: 95%
| term | value |
|---|---|
| ci_lower | 0.754 |
| ci_upper | 1.746 |
Confidence level: 95%
The median-unbiased estimate of uses the value of the noncentrality parameter for which the observed is the median (book p. 116).
HideShow
[1] 1.2439293.9.2 — Measures of Association Strength
Computing and
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
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
Df
as.factor(Condition) 2
Residuals 27HideShow
Mean Sq
as.factor(Condition) 23.333
Residuals 0.963HideShow
Sum Sq
as.factor(Condition) 46.667
Residuals 26.000HideShow
F value
as.factor(Condition) 24.231
Residuals HideShow
Pr(>F)
as.factor(Condition) 9.421e-07 ***
Residuals
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1HideShow
[1] 2HideShow
[1] 27HideShow
[1] 23.33333HideShow
[1] 0.962963Given the above information, Omega^2 can be obtained by extracting the necessary objects.
HideShow
[1] 0.6076459HideShow
[1] 0.6076459Similarly, for R^2
HideShow
[1] 0.6422018Or for Adjusted R^2
HideShow
[1] 0.61569833.9.2.1 — Confidence Intervals for Measures of Association Strength
The preceding calculations give sample and . DMAR also inverts the noncentral 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 |
| 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
[,1] [,2]
[1,] 66 34
[2,] 34 663.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
[1] 0.86HideShow
[1] 0.12HideShow
[1] 0.923.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.
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.812Now, using the new column of data in the data set, r, we perform the ANOVA as before.
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
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.
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")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
[1] 4.770605HideShow
[1] 32.00413Visualizing 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
[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).
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
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.29For 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
[1] 32.00413HideShow
[1] 29.00413HideShow
[1] 30.79357HideShow
[1] 28.2809The 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.02201The 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
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.308316HideShow
# 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.1746767Note 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.8773998Using 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
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.1589Figure 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).
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
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 ' ' 13.11 — Power of the Test: One-Way ANOVA
3.11.1 — Determining an Appropriate Sample Size
Power computed directly from the noncentral distribution
Computing the supposed noncentral parameter based on a set of supposed population means (for a hypothetical situation)
HideShow
[1] 5HideShow
[1] 0.1666667HideShow
[1] 0.4082483Using the above supposed scores, the effect size can be estimated as
follows, with
(length(Supposed.Group.Means)-1)/length(Supposed.Group.Means)
being used in order to use in the
denominator of the variance, rather than the default or typical
denominator ().
HideShow
[1] 0.4082483In R, we can find the exact power based on the area of the particular noncentral -distribution for the specified degrees of freedom by determining the area that is beyond the critical value from the central -distributoin as follows, for different sample sizes (some of this is calculated above but it is repeated here for completeness).
HideShow
[1] 100HideShow
[1] 400 450 500HideShow
[1] 3HideShow
[1] 450HideShow
[1] -50 0 50HideShow
[1] 40.82483HideShow
[1] 0.4082483HideShow
[1] 10HideShow
[1] 5HideShow
[1] 3.354131HideShow
[1] 0.4579923Here we use the above Constant values but specify a
different sample size (and then a new lambda results)
HideShow
[1] 25HideShow
[1] 12.5HideShow
[1] 3.123907HideShow
[1] 0.8827749Here we use the above Constant values but specify a
different sample size (and then a new lambda results)
HideShow
[1] 20HideShow
[1] 10HideShow
[1] 3.158843HideShow
[1] 0.7933118Trying to hone in on power of .80, we try n=21, which is
the smallest sample size that satisfies desired power.
HideShow
[1] 21HideShow
[1] 10.5HideShow
[1] 3.150411HideShow
[1] 0.8147697Power 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
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 groupHideShow
[1] 21Using the Brown and Miller results, we can plan with the median-unbiased estimate of , or with a one-sided lower confidence bound (book p. 139).
HideShow
[1] 0.4988501| 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)
| 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
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 groupHideShow
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 groupHideShow
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 groupTo 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 , deliver much less power than
the .80 that was planned for.
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 groupThe same plan three ways: base R, pwr, and DMAR
Take a medium effect for three groups, Cohen’s , and ask for 80% power at . All three routes below are the same noncentral- 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
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 per group, which it reports as a fraction; rounding up to whole participants per group gives .
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 groupHideShow
[1] 159DMAR’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 : 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 , 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 , we
convert via .
HideShow
[1] 0.05882353HideShow
| term | value |
|---|---|
| necessary_N | 158 |
| actual_power | 0.802 |
| noncentral_f_parm | 9.875 |
| true_f2 | 0.062 |
For accuracy in parameter estimation, suppose the anticipated
population 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.
| 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%
| 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%
For the one-way design, plan directly for the interval on at the same confidence level and target full width.
| 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%
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
Arel-Bundock V (2026). modelsummary: Summary Tables and Plots for Statistical Models and Data: Beautiful, Customizable, and Publication-Ready. doi:10.32614/CRAN.package.modelsummary https://doi.org/10.32614/CRAN.package.modelsummary. R package version 2.6.0, https://CRAN.R-project.org/package=modelsummary.
Champely S (2020). pwr: Basic Functions for Power Analysis. doi:10.32614/CRAN.package.pwr https://doi.org/10.32614/CRAN.package.pwr. R package version 1.3-0, https://CRAN.R-project.org/package=pwr.
Fox J, Weisberg S, Price B (2026). car: Companion to Applied Regression. doi:10.32614/CRAN.package.car https://doi.org/10.32614/CRAN.package.car. R package version 3.1-5, https://CRAN.R-project.org/package=car.
Iannone R, Cheng J, Schloerke B, Haughton S, Hughes E, Lauer A, François R, Seo J, Brevoort K, Roy O (2026). gt: Easily Create Presentation-Ready Display Tables. doi:10.32614/CRAN.package.gt https://doi.org/10.32614/CRAN.package.gt. R package version 1.3.0, https://CRAN.R-project.org/package=gt.
Kelley K (2026). DMAR: Design, Measurement, and Analysis in R (DMAR). R package version 1.2.0, https://kenkelley.org.
Komsta L, Novomestky F (2022). moments: Moments, Cumulants, Skewness, Kurtosis and Related Tests. doi:10.32614/CRAN.package.moments https://doi.org/10.32614/CRAN.package.moments. R package version 0.14.1, https://CRAN.R-project.org/package=moments.
Lüdecke D (2025). sjPlot: Data Visualization for Statistics in Social Science. doi:10.32614/CRAN.package.sjPlot https://doi.org/10.32614/CRAN.package.sjPlot. R package version 2.9.0, https://CRAN.R-project.org/package=sjPlot.
Maxwell S, Delaney H, Kelley K (2026). AMCP: Data Sets to Accompany Designing Experiments and Analyzing Data: A Model Comparison Perspective (Maxwell, Delaney, and Kelley, 2027, 4th Edition). doi:10.32614/CRAN.package.AMCP https://doi.org/10.32614/CRAN.package.AMCP. R package version 2.0.0, https://CRAN.R-project.org/package=AMCP.
Maxwell, S. E., Delaney, H. D., & Kelley, K. (2027). Designing Experiments and Analyzing Data: A Model Comparison Perspective (4th ed.). New York, NY: Routledge.
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. doi:10.32614/R.manuals https://doi.org/10.32614/R.manuals. https://www.R-project.org/.
Revelle W (2026). psych: Procedures for Psychological, Psychometric, and Personality Research. doi:10.32614/CRAN.package.psych https://doi.org/10.32614/CRAN.package.psych. R package version 2.6.5, https://CRAN.R-project.org/package=psych.
Sjoberg D, Larmarange J, Curry M, de la Rua E, Lavery J, Whiting K, Zabor E (2026). gtsummary: Presentation-Ready Data Summary and Analytic Result Tables. doi:10.32614/CRAN.package.gtsummary https://doi.org/10.32614/CRAN.package.gtsummary. R package version 2.5.1, https://CRAN.R-project.org/package=gtsummary.
Wickham H, Chang W, Henry L, Pedersen T, Takahashi K, Wilke C, Woo K, Yutani H, Dunnington D, van den Brand T (2026). ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics. doi:10.32614/CRAN.package.ggplot2 https://doi.org/10.32614/CRAN.package.ggplot2. R package version 4.0.3, https://CRAN.R-project.org/package=ggplot2.
Wickham H, François R, Henry L, Müller K, Vaughan D (2026). dplyr: A Grammar of Data Manipulation. doi:10.32614/CRAN.package.dplyr https://doi.org/10.32614/CRAN.package.dplyr. R package version 1.2.1, https://CRAN.R-project.org/package=dplyr.