Skip to main content

Appendix A — Working in R

Every chapter of this book loads a data frame, draws it, fits a model or does a test, and reads the output. The examples below come from the hands-on session of the DH801 course.

A.1 The task

The hands-on session used the R dataset ToothGrowth. The data come from E. W. Crampton, “The growth of the odontoblasts of the incisor tooth as a criterion of the vitamin C intake of the guinea pig”, The Journal of Nutrition 33(5): 491–504 (1947). Each guinea pig got one dose of vitamin C, as orange juice (OJ) or as ascorbic acid (VC). The outcome len is the length of the odontoblasts, the cells that make the tooth.

How does odontoblast length change with the dose of vitamin C, and is the change the same for the two supplements?

A.2 Data frames

A data frame is a table. Each row is one observation, and each column is one variable.

data(ToothGrowth)
head(ToothGrowth)
   len supp dose
1  4.2   VC  0.5
2 11.5   VC  0.5
3  7.3   VC  0.5
4  5.8   VC  0.5
5  6.4   VC  0.5
6 10.0   VC  0.5
str(ToothGrowth)
'data.frame':   60 obs. of  3 variables:
 $ len : num  4.2 11.5 7.3 5.8 6.4 10 11.2 11.2 5.2 7 ...
 $ supp: Factor w/ 2 levels "OJ","VC": 2 2 2 2 2 2 2 2 2 2 ...
 $ dose: num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...

There are 60 guinea pigs and 3 columns. len and dose are numbers. supp is a factor, a variable with a fixed set of levels.

Use $ to get one column, and square brackets to select rows.

unique(ToothGrowth$dose)
[1] 0.5 1.0 2.0
table(ToothGrowth$supp, ToothGrowth$dose)
    
     0.5  1  2
  OJ  10 10 10
  VC  10 10 10
oj <- ToothGrowth$len[ToothGrowth$supp == "OJ"]   # lengths for orange juice only
mean(oj)
[1] 20.66333

The design is balanced, with 10 animals in each of the 6 combinations of supplement and dose.

The tidyverse functions group_by() and summarise() calculate a summary for each group. The pipe |> sends the result of one step into the next step.

groups <- ToothGrowth |>
  group_by(supp, dose) |>
  summarise(n = n(), mean_len = mean(len), sd_len = sd(len), .groups = "drop")
groups
# A tibble: 6 × 5
  supp   dose     n mean_len sd_len
  <fct> <dbl> <int>    <dbl>  <dbl>
1 OJ      0.5    10    13.2    4.46
2 OJ      1      10    22.7    3.91
3 OJ      2      10    26.1    2.66
4 VC      0.5    10     7.98   2.75
5 VC      1      10    16.8    2.52
6 VC      2      10    26.1    4.80

A.3 Plots with ggplot

A ggplot() call starts from a data frame. The aesthetics in aes() connect columns to the axes and the colour. Layers such as geom_point() then draw the data.

ggplot(ToothGrowth, aes(dose, len, colour = supp)) +
  geom_jitter(width = 0.04, height = 0, size = 2, alpha = 0.8) +
  scale_colour_manual(values = c(OJ = "firebrick", VC = "steelblue")) +
  labs(x = "dose (mg/day)", y = "odontoblast length", colour = "supplement")
Figure A.1: Odontoblast length against the dose of vitamin C, for 60 guinea pigs (Crampton 1947). We move each point a little to the side, so that points do not overlap.

Length increases with dose for both supplements. At the two lower doses, orange juice gives longer cells. At 2 mg/day the means are 26.06 for orange juice and 26.14 for ascorbic acid.

A.4 A linear model

lm() fits a linear model. The formula len ~ dose * supp means: model len from dose, supp and their interaction. The interaction lets the slope for dose be different for each supplement.

model <- lm(len ~ dose * supp, data = ToothGrowth)
summary(model)

Call:
lm(formula = len ~ dose * supp, data = ToothGrowth)

Residuals:
    Min      1Q  Median      3Q     Max 
-8.2264 -2.8462  0.0504  2.2893  7.9386 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   11.550      1.581   7.304 1.09e-09 ***
dose           7.811      1.195   6.534 2.03e-08 ***
suppVC        -8.255      2.236  -3.691 0.000507 ***
dose:suppVC    3.904      1.691   2.309 0.024631 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.083 on 56 degrees of freedom
Multiple R-squared:  0.7296,    Adjusted R-squared:  0.7151 
F-statistic: 50.36 on 3 and 56 DF,  p-value: 6.521e-16

The output has one row for each coefficient:

  • (Intercept): the predicted length for orange juice at dose 0, 11.55. Dose 0 is outside the range of the data.
  • dose: the slope for orange juice, 7.81 units per mg/day.
  • suppVC: the change in intercept for ascorbic acid compared with orange juice, -8.26.
  • dose:suppVC: the change in slope for ascorbic acid. The slope for ascorbic acid is 7.81 + 3.90 = 11.72.

The last lines of the output (Residual standard error, Multiple R-squared and the F-statistic) describe the whole model. Chapter 12 explains each line. The functions coef(), confint() and residuals() return the parts of the fit.

confint(model)
                  2.5 %    97.5 %
(Intercept)   8.3820866 14.717913
dose          5.4167111 10.206146
suppVC      -12.7351061 -3.774894
dose:suppVC   0.5176438  7.290928

To check the model, plot(model) draws four diagnostic plots, which Chapter 13 explains.

A.5 Predictions on a grid

To draw the fitted lines, make a grid of new values with expand_grid(). Then use predict() with newdata. The grid must have columns with the same names as the predictors in the model.

grid <- expand_grid(dose = seq(0.5, 2, by = 0.05), supp = levels(ToothGrowth$supp))
grid$predicted <- predict(model, newdata = grid)
head(grid, 4)
# A tibble: 4 × 3
   dose supp  predicted
  <dbl> <chr>     <dbl>
1  0.5  OJ        15.5 
2  0.5  VC         9.15
3  0.55 OJ        15.8 
4  0.55 VC         9.74
Show code
ggplot(ToothGrowth, aes(dose, len, colour = supp)) +
  geom_jitter(width = 0.04, height = 0, size = 2, alpha = 0.6) +
  geom_line(data = grid, aes(y = predicted), linewidth = 1) +
  scale_colour_manual(values = c(OJ = "firebrick", VC = "steelblue")) +
  labs(x = "dose (mg/day)", y = "odontoblast length", colour = "supplement")
Figure A.2: The data with the fitted lines from the model len ~ dose * supp. The two lines have different slopes, because the model includes an interaction.

predict(model, newdata = grid, interval = "confidence") also gives a confidence interval for each predicted mean.

A.6 The tests in this book

Most tests in R take vectors and return an object that prints a short report. The table lists the functions of the book, in chapter order.

Comparison R function Chapter
Successes against a fixed probability binom.test(x, n) Chapter 3
Two paired means t.test(x, y, paired = TRUE) Chapter 4
Two independent means t.test(x, y) Chapter 4
Two paired samples, by ranks wilcox.test(x, y, paired = TRUE) Chapter 5
Two independent samples, by ranks wilcox.test(x, y) Chapter 6
Any statistic, by shuffles of the labels replicate(B, f(sample(labels))) Chapter 7
Two categorical variables chisq.test(table) Chapter 8
Two categorical variables, small counts fisher.test(table) Chapter 9
Two paired categorical outcomes mcnemar.test(table) Chapter 10
An outcome and several predictors lm(y ~ x1 + x2, data = df) Chapter 14
Correlation between predictors car::vif(model) Chapter 16
An outcome and many predictors, with a penalty glmnet::glmnet(X, y, alpha = ...) Chapter 17, Chapter 18
A 0/1 or count outcome and predictors glm(y ~ x, family = binomial) Chapter 20
A survival curve, censored times survfit(Surv(time, status) ~ group) Chapter 21
Two survival curves survdiff(Surv(time, status) ~ group) Chapter 21
A survival time and predictors coxph(Surv(time, status) ~ x1 + x2) Chapter 22

The hands-on session did the paired tests on the sleep data. In these data, 10 patients took two sleep drugs, and extra is the hours of extra sleep.

drug1 <- sleep$extra[sleep$group == 1]
drug2 <- sleep$extra[sleep$group == 2]
d <- (drug2 - drug1)[drug2 != drug1]       # remove zero differences
binom.test(sum(d > 0), length(d))$p.value  # sign test
[1] 0.00390625
wilcox.test(drug2, drug1, paired = TRUE, exact = FALSE)$p.value
[1] 0.009090698

The session also did a rank-sum test on the airquality data, to compare ozone in May and August in New York in 1973. na.omit() removes the missing values.

may    <- na.omit(airquality$Ozone[airquality$Month == 5])
august <- na.omit(airquality$Ozone[airquality$Month == 8])
wilcox.test(may, august, exact = FALSE)

    Wilcoxon rank sum test with continuity correction

data:  may and august
W = 127.5, p-value = 0.0001208
alternative hypothesis: true location shift is not equal to 0

Each test object is a list. Use $ to get one part, for example $p.value, $statistic or $conf.int. The chapters use this to put numbers from the output into the text.

A.7 Habits that help

  • Call set.seed() before a simulation, so that you get the same numbers each time.
  • Use str() and summary() on new data before you fit anything. Look for missing values (NA) and for numbers stored as text.
  • Draw the data before you do a test.
  • Use ?function_name to read the help page. The “Value” section lists what the function returns.