Appendix D: R Workflow Reference and Output Guide

This appendix is a complete reference for running statistical tests in R. It has two parts:

Use Part 1 while you are running your analysis. Use Part 2 when you are not sure what you are seeing.


Part 1: Workflow Cheat Sheet

Package Setup

Run the install.packages() lines once per computer. After that, only library() is needed at the start of each session.

# Install once per computer — this is the full course set (same as Chapter 6)
install.packages(c("tidyverse", "UsingR", "palmerpenguins", "reshape2",
                   "e1071", "nortest", "car", "vcd",
                   "afex", "emmeans", "effsize", "effectsize", "rstatix", "pwr",
                   "coin", "sandwich", "lmtest"))

# Load at the start of each session (load what a given analysis needs)
library(effsize)     # Cohen's d
library(effectsize)  # eta_squared, cohens_w
library(rstatix)     # effect sizes for non-parametric tests (loads its own eta_squared(), so write effectsize::eta_squared())
library(car)         # Levene's test, VIF
library(afex)        # repeated-measures / mixed ANOVA

Setup & Inspection

str(data)      # Variable names, types, and a preview
summary(data)  # Five-number summary plus mean

# Replace all three placeholders before running this template
data <- yourdata
group_column <- "your_group_variable"
score_column <- "your_outcome_variable"
data$group <- data[[group_column]]
data$score <- data[[score_column]]

Goal: Confirm correct data types (numeric vs. factor) before running tests.

Checking a Rival

Every result needs one rival explanation and a check you actually ran. Almost every rival check is one of these four moves.

# Pull out one group's scores (normality checks, means, histograms)
males <- data$score[data$sex == "Male"]
shapiro.test(males)

# 1. Unusual rows: find them, look, rerun without them, report both
rows <- which(data$score < 45)
data[rows, ]
keep <- data[-rows, ]
t.test(keep$score, mu = 72)

# 2. Same test inside each group: does the result hold in both?
men   <- subset(data, sex == "Male")
women <- subset(data, sex == "Female")
t.test(men$score, mu = 72)
t.test(women$score, mu = 72)

# 3. Do the groups differ on the rival?
aggregate(rival ~ group, data = data, FUN = mean)    # rival is a number
table(data$group, data$rival)                        # rival is a category

# 4. Hold the rival constant: add it to the model
summary(lm(score ~ group + rival, data = data))
# Does the group effect survive with the rival in the model?

Goal: Show whether your answer holds up once the rival is checked. Report the result both ways (with and without the rows, in each group, with and without the rival in the model), and never drop a row quietly.

T-Tests

Independent Samples (2 groups)

# Split the scores by group (use your own group labels in quotes)
g1 <- data$score[data$group == "group1_label"]
g2 <- data$score[data$group == "group2_label"]

# Normality checks (run all three)
hist(g1); hist(g2)
qqnorm(g1); qqline(g1)
qqnorm(g2); qqline(g2)
shapiro.test(g1); shapiro.test(g2)

# Boxplot
boxplot(score ~ group, data = data)

# Run t-test (Welch correction is on by default — handles unequal variances)
t.test(score ~ group, data = data)

# One-tailed, only if you predicted the direction in advance:
# t.test(score ~ group, data = data, alternative = "less")  # "less" = first group lower (groups go in alphabetical order)

# Descriptives
aggregate(score ~ group, data = data, FUN = mean)
aggregate(score ~ group, data = data, FUN = sd)

# Effect size
cohen.d(score ~ group, data = data)  # from effsize package

Not normal? If the histogram and Q-Q plot show clear non-normality (strong skew, outliers) and you have 30 or fewer per group, use the Mann-Whitney U instead. The link carries your names over. See the decision flowchart in Part 2.

Example report (the 15  Independent-Samples t-Test worked example): Students in method A (M = 16.58, SD = 2.61) scored lower than students in method B (M = 23.21, SD = 8.14), Welch’s t(16.04) = −2.88, p = .011, Cohen’s d = −1.06 (large effect). Welch’s df are usually not whole numbers; report them to two decimals.

Paired Samples (same participants twice)

# Define variables
pre  <- data$pre_score   # Replace with your pre column
post <- data$post_score  # Replace with your post column

# Normality checks on the DIFFERENCES
diffs <- post - pre
hist(diffs, main = "Histogram of Differences (Post - Pre)", xlab = "Difference")
qqnorm(diffs, main = "Q-Q Plot of Differences")
qqline(diffs)
shapiro.test(diffs)

boxplot(pre, post, names = c("Pre", "Post"))

t.test(post, pre, paired = TRUE)

# One-tailed, only if you predicted the direction in advance:
# t.test(post, pre, paired = TRUE, alternative = "greater")  # "greater" = post higher than pre

mean(pre);  sd(pre)
mean(post); sd(post)

cohen.d(post, pre, paired = TRUE, within = FALSE)  # within = FALSE gives d_z, the course convention

Not normal? If the histogram and Q-Q plot show clear non-normality (strong skew, outliers) and you have 30 or fewer pairs, use the Wilcoxon signed-rank instead. The link carries your names over. See the decision flowchart in Part 2.

Example report (the 16  Paired-Samples t-Test worked example): Participants scored higher post-test (Pre: M = 48.60, SD = 6.16; Post: M = 53.56, SD = 11.40), t(24) = 3.14, p = .004, Cohen’s d = 0.63 (medium effect).

One-Sample (compare to known mean)

hist(data$score, main = "Histogram of Scores", xlab = "Score")
qqnorm(data$score, main = "Q-Q Plot")
qqline(data$score)
shapiro.test(data$score)

t.test(data$score, mu = 100)  # Replace 100 with your known comparison value

# One-tailed, only if you predicted the direction in advance:
# t.test(data$score, mu = 100, alternative = "greater")  # "greater" = mean above mu

mean(data$score); sd(data$score)

# Effect size
(mean(data$score) - 100) / sd(data$score)  # Cohen's d: replace 100 with your comparison value

Not normal? If the histogram and Q-Q plot show clear non-normality (strong skew, outliers) and you have 30 or fewer scores, use the one-sample Wilcoxon signed-rank instead. The link carries your names over. See the decision flowchart in Part 2.

Example report (the 14  One-Sample t-Test worked example): The lattes (M = 163.85 mg, SD = 24.44 mg) contained significantly more caffeine than the claimed 150 mg, t(19) = 2.53, p = .020, Cohen’s d = 0.57 (medium effect).

ANOVA

One-Way ANOVA

data$group <- as.factor(data$group)

model <- aov(score ~ group, data = data)

# Normality checks on residuals
residuals_model <- residuals(model)
hist(residuals_model, main = "Histogram of Residuals", xlab = "Residuals")
qqnorm(residuals_model, main = "Q-Q Plot of Residuals")
qqline(residuals_model)
shapiro.test(residuals_model)

# Diagnostic plots (plot 2 = Q-Q; plot 3 = homogeneity)
plot(model)

# Homogeneity of variance
leveneTest(score ~ group, data = data)

# If Levene's p < .05 (unequal variances) → Welch's ANOVA instead of summary(model)
# oneway.test(score ~ group, data = data)

boxplot(score ~ group, data = data)

# If normality fails → consider Kruskal-Wallis
# kruskal.test(score ~ group, data = data)

summary(model)

TukeyHSD(model)  # If significant

tapply(data$score, data$group, mean)
tapply(data$score, data$group, sd)

effectsize::eta_squared(model)  # the prefix matters: rstatix has its own eta_squared() that prints only a bare number

Not normal? If the histogram and Q-Q plot show clear non-normality (strong skew, outliers) and you have 30 or fewer per group, use the Kruskal-Wallis instead. The link carries your names over. See the decision flowchart in Part 2.

Example report (the 17  One-Way ANOVA worked example): There was a significant effect of teaching method on scores, F(2, 27) = 5.44, p = .010, η² = .29 (large effect). Post-hoc Tukey tests showed method C > method A (p = .008); the other pairs did not differ significantly.

Regression

Simple Regression

plot(data$X, data$Y, pch = 19, col = "steelblue", xlab = "X", ylab = "Y")

model <- lm(Y ~ X, data = data)
abline(model, col = "red", lwd = 2)  # add the line now, while the scatterplot is still showing

# Normality of residuals
residuals_model <- residuals(model)
hist(residuals_model, main = "Histogram of Residuals", xlab = "Residuals")
qqnorm(residuals_model, main = "Q-Q Plot of Residuals")
qqline(residuals_model)
shapiro.test(residuals_model)

plot(model)  # 4 diagnostic plots

summary(model)
confint(model)  # 95% confidence interval for the slope

Effect size: R² from the summary output. Interpretation: .01 small, .09 medium, .25 large.

Example report (the 22  Simple Linear Regression worked example): Poverty rate significantly predicted teen birth rate, b = 2.03, t(49) = 6.93, p < .001, R² = .49.

Multiple Regression

model2 <- lm(Y ~ X1 + X2, data = data)

residuals_model2 <- residuals(model2)
hist(residuals_model2, main = "Histogram of Residuals", xlab = "Residuals")
qqnorm(residuals_model2, main = "Q-Q Plot of Residuals")
qqline(residuals_model2)
shapiro.test(residuals_model2)

plot(model2)

summary(model2)
# Look for: b values, p-values per predictor, Multiple and Adjusted R-squared
confint(model2)  # 95% confidence interval for each b

# Overlap between predictors (Ch 24)
library(car)
vif(model2)

Example report (Ch 24): Mother’s weight and smoking status together predicted birth weight, F(2, 993) = 44.90, p < .001, R² = .08, adjusted R² = .08. Both mother’s weight (b = 0.14, p < .001) and smoking (b = −8.35, p < .001) were significant predictors.

Correlation

plot(data$X, data$Y)
cor.test(data$X, data$Y)  # the output includes the 95% confidence interval for r

# Spearman (when assumptions are violated; see Ch 20)
cor.test(data$X, data$Y, method = "spearman")

Interpretation: r ≈ .10 small, .30 medium, .50 large.

Non-Parametric Tests

Mann-Whitney U (2 independent groups, non-normal)

wilcox.test(score ~ group, data = data)
aggregate(score ~ group, data = data, FUN = median)
aggregate(score ~ group, data = data, FUN = IQR)
rstatix::wilcox_effsize(data, score ~ group)  # Rosenthal's r

Wilcoxon Signed-Rank (paired, non-normal)

pre  <- data$pre_score   # Replace with your pre column
post <- data$post_score  # Replace with your post column

wilcox.test(post, pre, paired = TRUE)
median(pre); IQR(pre)
median(post); IQR(post)
# Effect size: still required. See Ch 13 for which one and how

Wilcoxon Signed-Rank (one sample, non-normal)

The rank version of the one-sample t. Same test as the paired version: the paired test runs it on post − pre against 0.

wilcox.test(data$score, mu = 100, exact = FALSE)  # Replace 100 with your comparison value
median(data$score); IQR(data$score)
rstatix::wilcox_effsize(data, score ~ 1, mu = 100)  # Rosenthal's r

Kruskal-Wallis (3+ groups, non-normal)

kruskal.test(score ~ group, data = data)
pairwise.wilcox.test(data$score, data$group, p.adjust.method = "BH")
kruskal_effsize(data, score ~ group)

Effect size: η²_H (from kruskal_effsize()) ≈ .01 small, .06 medium, .14 large.

Chi-Square Tests

# Goodness-of-fit
chisq.test(obs, p = expected_prop)  # leave out p only if you expect equal proportions
cohens_w(obs, p = expected_prop)

# Independence
table1 <- table(data$var1, data$var2)
chisq.test(table1)
vcd::assocstats(table1)  # Cramér's V is the last line (uses the uncorrected χ², see Ch 21)

# Small samples → Fisher's exact
fisher.test(table1)
# Effect size: still required. See Ch 21 and Ch 27

Quick Reference

Comparison Test Code
2 independent groups (normal) Independent t-test t.test(score ~ group, data = data)
2 independent groups (non-normal) Mann-Whitney U wilcox.test(score ~ group, data = data)
2 paired groups (normal) Paired t-test t.test(post, pre, paired = TRUE)
2 paired groups (non-normal) Wilcoxon Signed-Rank wilcox.test(post, pre, paired = TRUE)
One sample vs. a set number (non-normal) Wilcoxon Signed-Rank (one sample) wilcox.test(data$score, mu = 100)
3+ groups (normal) One-Way ANOVA aov(score ~ group, data = data)
3+ groups (unequal variances) Welch’s ANOVA oneway.test(score ~ group, data = data)
3+ groups (non-normal) Kruskal-Wallis kruskal.test(score ~ group, data = data)
One categorical variable Chi-Square GoF chisq.test(obs, p = expected_prop)
Two categorical variables Chi-Square Independence chisq.test(table(v1, v2))
Two continuous Correlation cor.test(X, Y)
Two continuous (assumptions violated) Spearman correlation cor.test(X, Y, method = "spearman")
Predict Y from X Simple Regression lm(Y ~ X, data = data)

Part 2: Reading Your Output

The hardest part of assumption-checking is not running the code — it is knowing what you are looking at. This section shows you what each plot and test result should look like when things are fine, what problems look like, and what to do about them.

Histograms

A histogram shows the shape of your data’s distribution. For most parametric tests you want a distribution that is roughly bell-shaped — symmetric, single peak, no extreme tails.

Histogram of normally distributed data showing a symmetric bell shape.

A roughly symmetric, bell-shaped histogram. The bars rise toward the center and taper off on both sides. This is what you want to see.

Histogram of right-skewed data with a long right tail.

A right-skewed histogram. Most values are bunched at the low end with a long tail to the right. This pattern suggests the normality assumption may not hold — check the Q-Q plot and Shapiro-Wilk.

What to look for:

  • Symmetric, bell-shaped: normal assumption is plausible. Proceed with the parametric test.
  • Strong skew (long tail on one side): flag this. Check the Q-Q plot and Shapiro-Wilk. If the sample is large (n > 30 per group), mild skew is usually not a serious problem for t-tests and ANOVA due to the Central Limit Theorem.
  • Bimodal (two peaks): suggests you may have two subgroups mixed together. Worth investigating before running the test.
  • Very flat (uniform): not a normal distribution, but may not matter much at moderate sample sizes.

Histograms are less reliable with small samples (n < 30). With 15 observations a normal distribution can easily look irregular. The Q-Q plot is more informative at small n.


Q-Q Plots

A Q-Q (quantile-quantile) plot compares your data to what a normal distribution would look like. The diagonal reference line represents perfect normality. Points that fall close to the line indicate normally distributed data.

Q-Q plot with points following the diagonal reference line closely.

A good Q-Q plot. The points follow the diagonal reference line closely, with minor deviation at the ends. This is normal and expected — no action needed.

Q-Q plot showing right-skewed data curving away from the diagonal.

A Q-Q plot with right-skewed data. The points curve upward at the right end, pulling away from the reference line. This indicates a long right tail.

Reading the patterns:

Pattern What it means
Points follow the line closely Data are approximately normal — proceed
Points curve upward at the right Right skew — consider log or square-root transformation
Points curve downward at the left Left skew
S-shaped curve (both ends deviate) Heavy tails (more extreme values than normal)
Points deviate at one end only One extreme outlier; check that value

How much deviation is OK? Some wobble at the ends is always present, especially with small samples. Base R’s qqnorm() draws no confidence bands; car::qqPlot() does, and if the points stay within those bands, normality is plausible. A clear, systematic curve is more concerning than scattered end-points.


Boxplots

Boxplots show the median (center line), interquartile range (the box), and the range of non-outlier values (whiskers). Points beyond the whiskers are flagged as potential outliers.

Boxplot showing two symmetric groups with similar spread and no outliers.

A good boxplot. Both boxes are roughly symmetric around the median, the whiskers are similar in length on both sides, and there are no outlier points. The two groups also have similar spread (box widths).

Boxplot showing outliers in Group A and very different spread between groups.

A problematic boxplot. Group A has two extreme outliers above the upper whisker. Group B has a much wider box than Group A, suggesting unequal variances. Both issues warrant attention before running a parametric test.

What to look for:

  • Symmetric box: the median line is near the middle of the box. Good sign.
  • Asymmetric box: the median is pushed to one side — suggests skew.
  • Outlier points (dots beyond whiskers): a few outliers are normal. Many outliers, or outliers that are extreme, can heavily influence means and standard deviations. Identify them with which(data$score > X) and investigate whether they are data errors.
  • Very different box sizes between groups: this indicates unequal variances (heteroscedasticity). R’s t.test() applies Welch’s correction by default, which handles this. For ANOVA, check Levene’s test.

Shapiro-Wilk Test

The Shapiro-Wilk test formally tests H₀: the data are normally distributed. A significant result (p < .05) suggests non-normality.

Example output from R (the Chapter 14 latte data, n = 20):

latte_data <- read.csv("https://jkoxford-a11y.github.io/awesomesaucestats/data/ch14_lattes.csv")
shapiro.test(latte_data$caffeine_mg)
    Shapiro-Wilk normality test

data:  latte_data$caffeine_mg
W = 0.97432, p-value = 0.8421

p = .842 → fail to reject H₀ → no evidence against normality → proceed with parametric test.

A strongly right-skewed sample (the Chapter 14 homework-time data, n = 18):

hw_data <- read.csv("https://jkoxford-a11y.github.io/awesomesaucestats/data/ch14_homework_time.csv")
shapiro.test(hw_data$minutes)
    Shapiro-Wilk normality test

data:  hw_data$minutes
W = 0.51596, p-value = 1.106e-06

1.106e-06 is R’s scientific notation for 0.000001106, so report p < .001 → reject H₀ → evidence of non-normality → examine histogram and Q-Q plot; consider non-parametric alternative.

The Shapiro-Wilk test has a sample-size problem. With small samples (n < 20), it has low power — it can miss real non-normality and return a non-significant result even when the distribution is far from normal. With large samples (n > 50 or so), it becomes overly sensitive — it will flag trivial deviations that have no practical impact on your test. Always use the histogram and Q-Q plot alongside Shapiro-Wilk. If the visual checks look fine but Shapiro-Wilk is significant, and n is large, the visual evidence usually matters more.


Levene’s Test

Levene’s test checks the homogeneity of variance assumption: H₀: all groups have equal variances.

Example output (the Chapter 17 teaching-methods data, three groups):

anova_data <- read.csv("https://jkoxford-a11y.github.io/awesomesaucestats/data/ch17_teaching_methods.csv")
anova_data$method <- as.factor(anova_data$method)
leveneTest(score ~ method, data = anova_data)
Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  2  0.3493 0.7083
      27               

p = .708 → fail to reject H₀ → variances are not significantly different → assumption is met. R labels the row group whatever your grouping variable is called.

The Chapter 15 teaching-methods data (two groups) give a different result:

t_data <- read.csv("https://jkoxford-a11y.github.io/awesomesaucestats/data/ch15_teaching_methods.csv")
t_data$method <- as.factor(t_data$method)
leveneTest(score ~ method, data = t_data)
Levene's Test for Homogeneity of Variance (center = median)
      Df F value  Pr(>F)  
group  1   5.889 0.02311 *
      24                  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

p = .023 → variances differ significantly.

What to do:

  • For t-tests: do not run Levene’s test first. R’s t.test() is Welch’s test by default (var.equal = FALSE), which does not assume equal variances, so the Levene result would not change which test you run (15  Independent-Samples t-Test). Report it as a Welch’s t-test.
  • For ANOVA: a significant Levene’s test means switching to Welch’s one-way ANOVA (oneway.test(score ~ group, data = data, var.equal = FALSE)). Kruskal-Wallis does not fix unequal variances: it compares whole distributions (13  Non-parametric Alternatives).

The Four plot(model) Diagnostic Plots

When you run plot(model) on a regression or ANOVA model, R produces four plots. You will be prompted to press Enter between plots. Here is what each one shows and what to look for.

Plot 1: Residuals vs. Fitted

This plot checks two assumptions: linearity (the relationship between X and Y is linear) and homoscedasticity (equal variance across all fitted values).

Residuals vs fitted plot showing random scatter around zero with a flat red line.

Residuals vs. Fitted — good. The points are scattered randomly around the horizontal zero line. The red smoothing line is approximately flat. There is no systematic pattern.

Residuals vs fitted plot showing a fan shape where spread increases with fitted values.

Residuals vs. Fitted — fan shape. The spread of residuals increases as fitted values increase. This is heteroscedasticity — the variance is not equal across the range of the predictor.

Residuals vs fitted plot showing a U-shaped curve indicating non-linearity.

Residuals vs. Fitted — U-shape. The red line curves, indicating the relationship between X and Y is not linear. A quadratic or transformed predictor may be needed.

What to look for:

Pattern in Plot 1 What it means What to do
Random scatter, flat red line Assumptions met Proceed
Fan shape (spread increases) Heteroscedasticity Transform Y (log, sqrt), or use robust SEs (sandwich package)
U-shape or curve Non-linearity Add quadratic term; transform X
A few labeled points Potential outliers/influential cases Investigate those observations

Plot 2: Normal Q-Q of Residuals

This is the same Q-Q plot described earlier, applied to the model residuals rather than raw scores. For regression and ANOVA, it is the residuals that need to be normal, not the raw data. Interpret it exactly as described in the Q-Q section above.

Plot 3: Scale-Location

This plot also checks homoscedasticity. It shows the square root of the absolute standardized residuals against fitted values. A flat red line means variance is roughly equal across the range of fitted values.

Scale-location plot with a flat red line indicating equal variance.

Scale-Location — good. The red smoothing line is approximately flat, indicating roughly equal variance across all fitted values.

Scale-location plot with an upward-sloping red line indicating heteroscedasticity.

Scale-Location — problem. The red line slopes upward, confirming that variance increases with fitted values (the same fan pattern visible in Plot 1).

Plot 4: Residuals vs. Leverage

This plot identifies influential observations — individual data points that have an unusually large effect on the regression line. Points with high leverage (far from the mean of X) and large residuals are flagged.

Cook’s distance dashed curves appear on the plot. Any point outside those curves warrants investigation. The rules of thumb from Cook’s distance: the influence number: Cook’s D > 1 is almost certainly influential; D > 4/n is worth a look.

What to do with influential points:

  1. Check whether the value is a data entry error — if so, correct or remove it.
  2. If it is a legitimate data point, report the analysis both with and without the point and note whether the conclusions change.
  3. Do not remove points simply because they are outliers or because they change your results. Report them transparently.

Decision Flowchart: Parametric or Non-Parametric?

After checking your assumptions, use this logic:

Is your outcome variable continuous or ordinal?
│
├─ Ordinal → Use non-parametric test (skip normality checks)
│
└─ Continuous →
   │
   ├─ Histogram and Q-Q plot look roughly normal,
   │  or n > 30 per group with mild skew only?
   │   → Parametric test (Central Limit Theorem covers mild skew)
   │
   └─ Clear non-normality (strong skew, outliers) in the histogram
      and Q-Q plot, in a small sample (n ≤ 30 per group)?
       │
       ├─ 2 independent groups → Mann-Whitney U
       ├─ 2 paired groups      → Wilcoxon Signed-Rank
       ├─ 1 sample vs. a number → Wilcoxon Signed-Rank (one sample)
       └─ 3+ groups            → Kruskal-Wallis

These are guidelines, not rigid rules. In practice, t-tests and ANOVA are reasonably robust to moderate violations of normality, especially with equal group sizes. The decision to use a non-parametric test is a judgment call — document your reasoning.


Common Error Fixes

Error message Likely cause Fix
object 'scroe' not found Typo in an object or column name Check spelling with names(data)
'x' must be numeric or argument is not numeric or logical: returning NA The score column was read in as text data$score <- as.numeric(as.character(data$score)), then check for new NAs. Plain as.numeric() on a factor returns the level codes (1, 2, 3), not the numbers
grouping factor must have exactly 2 levels Too many groups, or extra factor level Check unique(data$group)
Warning: Chi-squared approximation may be incorrect Some expected counts are below 5 Use fisher.test() instead
could not find function "leveneTest" Package not loaded Add library(package_name) at top
eta_squared() prints a bare number, or unused argument (partial = TRUE) rstatix was loaded after effectsize, so its own eta_squared() took over the name Use effectsize::eta_squared(model)
all 'x' values are identical (from shapiro.test()) No variation in the scores Check your data: every value is the same