Probability and Statistics · Chapter 2

Chapter 2
Describing data

Lectures 3–4 · centre, spread, shape, and pictures that tell the truth

Cartoon: crossing a riverA stick figure stands on a river bank holding a sign that reads: average depth 3 feet. Out in the middle of the river, a second figure is in water up to the neck and says: The average forgot to mention the middle. avg 3 ftThe average forgot tomention the middle.
a centre without a spread can be dangerous

Before anyone can predict from data or infer anything about the mechanism behind them, someone has to look at the data. That sounds trivial. It isn't. A table of 300 numbers tells the human eye almost nothing, and a single summary number can hide exactly the thing that matters. An average depth of three feet doesn't mean you can wade across the river.

This chapter gives you the tools for looking: numbers that summarize where data sit (the centre), how much they vary (the spread), and what pattern they make (the shape), and the pictures that show all three at once. Along the way we'll meet a geyser that keeps two timetables, a physicist who measured the speed of light slightly wrong, and a university that seemed to discriminate against women until someone looked more closely. Every named dataset is real and built into R, so you can explore them yourself.

Every summary in this chapter comes with three things:

  1. a way to compute it by hand, step by step, so that you know exactly what it is (and can do it in an exam);
  2. the R code that computes it, so that you can use it on real datasets with hundreds of values;
  3. its strengths and weaknesses, because no single summary is best for every job.

The by-hand answers and the R answers always agree. If yours don't, that's a sign to look again at one of the steps.

Describing data is not an end in itself: it is the first step of both of the course's big goals. For prediction, a summary of past data is the raw material of every forecast: the centre of a distribution is our best single guess for the next value (Section 2.2 makes this precise), and the spread tells us how far off that guess is likely to be. For inference, the pictures and summaries of a sample are our first clues about the mechanism that produced it: two peaks hint at two hidden groups, a difference between boxplots hints at a real effect, and a pattern that reverses when the data are split warns us that something else is at work. Keep both questions in mind as you read: what would I predict for the next case? and what does this suggest about the process behind the data?

Think About It: What Would You Want to Know?

A friend tells you, "the average commute time in my city is 30 minutes." What else would you want to know before deciding whether you'd enjoy living there? Try to name three different things. By the end of the chapter you'll have a word, a number and a picture for each of them.

Typical answers: How much does it vary? (Is it always 30, or sometimes 10 and sometimes 90? That's spread.) Is the average dragged up by a few people with very long commutes? (That's shape, especially skewness, and the difference between the mean and the median.) Are there two groups, such as drivers and cyclists, with very different times? (That's bimodality, and comparing groups with side-by-side boxplots.) What about my particular route? (That's position: where one value sits within the distribution.)

Lecture 3 — Shape, centre and spread

2.1 Distributions: the shape of data

A geyser with two timetables

Old Faithful, in Yellowstone National Park, is the most famous geyser in the world. Every hour or two it shoots water dozens of metres into the air, and crowds gather to watch. Park rangers post a prediction of the next eruption so visitors know when to arrive. How do they predict it?

R's faithful dataset records 272 eruptions: how long each lasted, and how long visitors then waited for the next one. Here are the eruption lengths.

Example 2.1: Old Faithful's Eruptions ★ lecture example

Summarize the 272 eruption lengths in faithful, then draw a histogram. What does the picture reveal that the summary hides?

summary() gives six numbers at once: the smallest value, the first quartile, the median, the mean, the third quartile and the largest value. (All of these are defined later in the chapter.)

R
summary(faithful$eruptions)       # minutes
output
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  1.600   2.163   4.000   3.488   4.454   5.100 

Reading the summary on its own, you might imagine a "typical" eruption of about 3.5 minutes, with lengths spread fairly evenly from 1.6 to 5.1 minutes. Now look at the picture:

R
ggplot(faithful, aes(x = eruptions)) +
  geom_histogram(binwidth = 0.2, boundary = 1.6) +
  labs(x = "eruption length (minutes)", y = "number of eruptions")
Histogram of 272 Old Faithful eruption lengths in minutes, from about 1.5 to 5Histogram of 272 Old Faithful eruption lengths in minutes, from about 1.5 to 5. There are two separate clusters: a smaller one around 2 minutes and a larger one around 4 to 4.5 minutes, with very few eruptions near the mean of 3.5 minutes. 0 10 20 30 40 2 3 4 5 eruption length (minutes) number of eruptions

Each bar covers an interval 0.2 minutes wide, and its height is the number of eruptions whose length fell in that interval. The eruptions come in two kinds: short ones of about 2 minutes, and long ones of about 4 to 4.5 minutes. Very few eruptions last anywhere near the "average" 3.5 minutes. The summary numbers described an eruption that hardly ever happens.

The two clusters matter for prediction: after a short eruption the geyser recharges sooner, and after a long one visitors wait longer. Rangers use the length of the last eruption to predict the next. One look at the histogram explains why that works, and no summary number would have suggested it.

Data: R's faithful (W. Härdle, Smoothing Techniques, 1991; A. Azzalini and A. W. Bowman, Applied Statistics, 1990).

The pattern of values in a dataset (which values occur, and how often) is its distribution (Section 1.4). A histogram is the standard picture of the distribution of a numerical variable.

Drawing a histogram

A histogram is built from a frequency table: a list of intervals and the number of observations in each.

Definition: Frequency Table and Histogram

Divide the range of a numerical variable into adjacent intervals of equal width, called bins or classes. The frequency of a bin is the number of observations in it, and its relative frequency is the frequency divided by the total number of observations n.

A histogram draws, for each bin, a bar whose base is the bin and whose height is its frequency (or relative frequency). The bars touch, because the bins cover the number line without gaps.

In a density histogram, each bar's height is density=relative frequencybin width, so that the area of each bar is its relative frequency and the total area of all the bars is 1.

The bars of a histogram touch, unlike the bars of a bar chart for categories (Section 2.5), because a numerical variable runs continuously along the number line. A gap in a histogram means "no observations here", which is information.

Idea: Algorithm: A Histogram by Hand

  1. Find the range. Identify the smallest and largest observations.
  2. Choose the bins. Pick a convenient bin width (5 to 15 bins is usual for small datasets) and a starting point at or just below the minimum. Write down every bin as an interval.
  3. Decide the endpoint rule. A value that lands exactly on a boundary must go in only one bin. In these notes we include the left endpoint: the bin [a,b) contains values with a≤x<b. Say which rule you used.
  4. Tally. Go through the data once, making a tally mark in the bin of each observation. Check that the counts add up to n.
  5. Draw the axes. The variable goes on the horizontal axis, with the bin boundaries marked; frequency (or density) goes on the vertical axis, starting at 0.
  6. Draw the bars. One bar per bin, as wide as the bin, as tall as its count, touching its neighbours. Label both axes, with units.

Example 2.2: A Histogram by Hand ★ lecture example

In the first of his five experiments in 1879, Albert Michelson made 20 measurements of the speed of light (more about him in Example 2.8). Recorded as the speed in km/s minus 299,000, they were

850, 740, 900, 1070, 930, 850, 950, 980, 980, 880, 1000, 980, 930, 650, 760, 810, 1000, 1000, 960, 960.

Make a frequency table and draw a histogram by hand, using bins of width 100 starting at 600. Then reproduce it in R and describe the shape.

Step 1, range. The smallest value is 650 and the largest 1070.

Steps 2 and 3, bins. Bins of width 100 starting at 600 are [600,700), [700,800), [800,900), [900,1000) and [1000,1100). These cover 650 to 1070. Using the left-endpoint rule, the value 900 belongs to [900,1000) and the three values of 1000 belong to [1000,1100).

Step 4, tally. It's easiest to sort the data first: 650, 740, 760, 810, 850, 850, 880, 900, 930, 930, 950, 960, 960, 980, 980, 980, 1000, 1000, 1000, 1070. Then count the values in each bin:

bin values freq. rel. freq.
[600,700) 650 1 0.05
[700,800) 740, 760 2 0.10
[800,900) 810, 850, 850, 880 4 0.20
[900,1000) 900, 930, 930, 950, 960, 960, 980, 980, 980 9 0.45
[1000,1100) 1000, 1000, 1000, 1070 4 0.20
total 20 1.00

The frequencies add up to 20, as they must. Each relative frequency is the frequency divided by 20. For a density histogram, divide each relative frequency by the bin width, 100: the densities are 0.0005, 0.0010, 0.0020, 0.0045 and 0.0020 per km/s.

Steps 5 and 6, draw. A bar of height 1 over 600 to 700, height 2 over 700 to 800, and so on. In R, hist() draws the same picture. The argument right = FALSE tells it to use left-closed bins, [a,b), matching our rule:

R
expt1 <- morley$Speed[morley$Expt == 1]
expt1
h <- hist(expt1, breaks = seq(600, 1100, by = 100), right = FALSE,
          main = NULL, xlab = "speed (km/s minus 299,000)", ylab = "frequency")
h$counts          # the frequencies, bin by bin
output
 [1]  850  740  900 1070  930  850  950  980  980  880 1000  980  930
[14]  650  760  810 1000 1000  960  960
[1] 1 2 4 9 4
Histogram of Michelson's 20 measurements from experiment 1, with bins of width 100 from…Histogram of Michelson's 20 measurements from experiment 1, with bins of width 100 from 600 to 1100. Bar heights are 1, 2, 4, 9 and 4. The tallest bar is between 900 and 1000, with a tail of shorter bars to the left. speed (km/s minus 299,000) frequency 600 700 800 900 1000 1100 0 2 4 6 8

The counts 1, 2, 4, 9, 4 match our table.

Shape. The distribution has a single peak in [900,1000), and a tail stretching out to the left, towards the lower values. It is unimodal and left-skewed (these words are defined below).

Why the endpoint rule matters. R's default is the opposite rule, (a,b]. With right = TRUE, the 900 moves down a bin and the three 1000s move down too, giving counts 1, 2, 5, 11, 1: a noticeably different picture from the same data. With only 20 values, several of which sit exactly on bin boundaries, small choices change the histogram. That's worth remembering whenever you read one.

A histogram depends on two choices you make: the bin width and the starting point. Too wide and every detail is smoothed away; too narrow and the picture is all noise. Try it on Old Faithful and three other datasets from this chapter.

Same data, different bins

A histogram depends on choices you make: how wide the bins are and where the first one starts. Pick one of the real datasets from this chapter and move the sliders. Watch peaks appear and vanish. The tick marks under the axis show the actual observations, which never change.

A density histogram of the chosen dataset with adjustable bin width and starting point…A density histogram of the chosen dataset with adjustable bin width and starting point, and a rug of tick marks showing each observation.

There is no single correct bin width. A good habit is to try several, and to trust only the features (peaks, gaps, tails) that survive every reasonable choice.

Describing a distribution

When you describe a distribution, describe three things:

Statisticians use a small vocabulary for shape. It's worth learning exactly, because "skewed to the right" is easy to get backwards.

Definition: Words for Shape

  • Modality. A mode of a histogram is a peak: a bar (or cluster of bars) taller than its neighbours. A distribution with one clear peak is unimodal, with two is bimodal, and with more is multimodal. One with no peak at all, where every bin has about the same height, is uniform.
  • Symmetry. A distribution is symmetric if its left and right halves are roughly mirror images.
  • Skewness. A distribution is right-skewed (or positively skewed) if it has a long tail stretching to the right, towards large values, and left-skewed (or negatively skewed) if the long tail stretches to the left. The direction of skew is the direction of the long tail, not of the peak.
  • Gaps and outliers. A gap is a stretch with no observations; an outlier is an observation far from the rest (Section 2.4 gives a rule).

Explore the shapes below. Pay attention to where the mean and median sit for each one: the relationship between them is the quickest numerical clue to the shape.

A gallery of shapes

Choose a shape. The histogram shows 400 observations with that shape. The solid line marks the mean and the dashed line the median. Read the description, then try to predict, before you click, where the mean and median will sit for the next shape.

Histogram of the chosen shape with the mean and median markedHistogram of the chosen shape with the mean and median marked.

Most quantities that can't go below zero but occasionally get very large (incomes, waiting times, pollution levels, drug concentrations) are right-skewed. Left skew is rarer, and usually appears when there is a natural upper limit that most values crowd against (scores on an easy test), or when a few values come out unusually low (Michelson's measurements).

Watch Out: Naming the Skew

Students often name the skew after the side where the peak is. It's the other way round: name it after the tail. A histogram with a tall peak on the left and a long tail to the right is right-skewed. A quick check: in a right-skewed distribution, the mean is usually to the right of the median, pulled along by the tail.

Histograms: strengths and weaknesses

feature histograms
Used for the distribution of one numerical variable
Shows well shape (peaks, skew, gaps), where most values lie, how spread out they are
Strengths easy to read; shows features no summary number can, such as two peaks (Old Faithful)
Weaknesses the picture depends on the bin width and starting point; individual values are lost inside bars; poor for small datasets (under about 20 values); comparing many groups means many separate histograms

Check Yourself

A histogram of the heights of everyone in a building shows two peaks. What is the most likely explanation?

In a density histogram, a bin from 20 to 30 contains 5 of 200 observations. What is the height of its bar?

Think About It: What Made the Shape?

A histogram's shape is a clue about the mechanism behind the data. For each shape, suggest a mechanism that could produce it: (a) the waiting times at a doctor's surgery are right-skewed; (b) the ages of people at a children's birthday party are bimodal; (c) scores on a very easy quiz are left-skewed. Then say how the shape would affect your prediction for the next person.

(a) Most patients are seen quickly, but now and then a complicated case or an emergency holds everyone up, creating a long right tail; for a prediction, the median wait is more typical than the mean, but you should allow for a long wait. (b) Two groups, children and the adults who brought them; a single "average age" predicts nobody, so first predict which group the next guest is in. (c) Most students get nearly full marks, and a few who didn't prepare score low; the best guess is high, and the uncertainty is mostly on the low side. In each case, reasoning about the mechanism (inference) improves the prediction.

Key Takeaways

  • Always draw the data before summarizing them.
  • A histogram is built from a frequency table: choose bins, decide the endpoint rule, tally, draw touching bars.
  • Describe a distribution by its shape, centre and spread.
  • Right-skewed means a long tail to the right. Two peaks often signal two groups.
  • A histogram's appearance depends on the bins: try several, and trust only the features that survive.

2.2 Centre: what is a typical value?

Mean and median

Suppose we have observations x1,x2,…,xn. The subscript i in xi just labels the observations in the order they were recorded. When we sort them from smallest to largest, we write x(1)≤x(2)≤⋯≤x(n): the brackets around the subscript mean "the ith smallest". There are two classic ways to describe the centre.

Definition: Sample Mean

The sample mean is the ordinary average: x‾=x1+x2+⋯+xnn=1n∑i=1nxi. In R: mean(x).

Definition: Sample Median

The sample median x̃ is the middle value of the sorted data.

  • If n is odd, it is the observation in position n+12: x̃=x((n+1)/2).
  • If n is even, there are two middle observations, in positions n2 and n2+1, and the median is their average: x̃=12(x(n/2)+x(n/2+1)).

In R: median(x).

The two measure "typical" in different ways. The mean is the balance point of the data: put an equal weight at each observation on a see-saw, and the mean is where it balances. A value far from the others sits at the end of a long lever, so it has a lot of influence. The median is the halfway point: half the observations are at or below it and half at or above. It only cares about the order of the values, not how far out the extreme ones are.

Example 2.3: Mean and Median by Hand ★ lecture example

(a) Five samples from a contaminated well have toxin concentrations 12.1, 9.8, 15.3, 11.0 and 10.4 ng/mL. (b) Insecticide A was tested on 12 plots, leaving 10, 7, 20, 14, 14, 12, 10, 23, 17, 20, 14 and 13 insects. For each dataset, find the mean and median by hand, then check in R.

(a) Toxin concentrations, n=5.

Mean. The values add to 12.1+9.8+15.3+11.0+10.4=58.6, so dividing by 5 gives x‾=58.65=11.72 ng/mL.

Median. Sort: 9.8, 10.4, 11.0, 12.1, 15.3. With n=5 (odd), the median is in position (5+1)/2=3, so x̃=11.0 ng/mL.

The mean is a little larger than the median, because 15.3 is further above the middle than 9.8 is below it.

(b) Insect counts, n=12.

Mean. The sum is 10+7+20+14+14+12+10+23+17+20+14+13=174, so x‾=17412=14.5 insects.

Median. Sort: 7, 10, 10, 12, 13, 14, 14, 14, 17, 20, 20, 23. With n=12 (even), the two middle values are in positions 12/2=6 and 7. Both are 14, so x̃=14+142=14 insects.

In R:

R
conc  <- c(12.1, 9.8, 15.3, 11.0, 10.4)
mean(conc); median(conc)
sprayA <- InsectSprays$count[InsectSprays$spray == "A"]
sprayA
sort(sprayA)
mean(sprayA); median(sprayA)
output
[1] 11.72
[1] 11
 [1] 10  7 20 14 14 12 10 23 17 20 14 13
 [1]  7 10 10 12 13 14 14 14 17 20 20 23
[1] 14.5
[1] 14

The R answers match the hand calculations.

A picture of both datasets. Each dot is one observation; the solid line is the mean and the dashed line the median:

R
two <- rbind(data.frame(data = "toxin (ng/mL)", x = conc),
             data.frame(data = "insects, spray A", x = sprayA))
lines <- aggregate(x ~ data, data = two, FUN = function(v) c(mean = mean(v), median = median(v)))
lines <- data.frame(data = lines$data, mean = lines$x[, "mean"], median = lines$x[, "median"])
two$stack <- ave(two$x, two$data, two$x, FUN = seq_along)   # stack repeated values
ggplot(two, aes(x = x, y = stack)) +
  geom_point(size = 3) +
  geom_vline(data = lines, aes(xintercept = mean)) +
  geom_vline(data = lines, aes(xintercept = median), linetype = "dashed") +
  geom_text(data = lines, aes(x = mean, y = 3.4, label = "mean"), hjust = -0.15, size = 3.8) +
  geom_text(data = lines, aes(x = median, y = 3.4, label = "median"), hjust = 1.15, size = 3.8) +
  facet_wrap(~ data, scales = "free_x", ncol = 1) +
  scale_y_continuous(NULL, breaks = NULL, limits = c(0.5, 3.8)) + labs(x = NULL)
Two dot plotsTwo dot plots. Bottom, the five toxin concentrations from 9.8 to 15.3, with the mean line at 11.72 slightly to the right of the median line at 11.0, pulled by the value 15.3. Top, the twelve insect counts from 7 to 23, with the mean at 14.5 just to the right of the median at 14, and three dots stacked at 14. mean median mean median toxin (ng/mL) insects, spray A 10 12 14 10 15 20

In both datasets the mean sits slightly right of the median: a value far out on the right (15.3 ng/mL, or 23 insects) pulls the balance point towards it, but doesn't move the middle value.

For symmetric data the mean and median agree; for skewed data they don't. Which one should you report? That depends on the question you are answering.

Example 2.4: Ozone: Mean or Median? ★ lecture example

Find the mean and median of daily ozone in airquality, and explain why they differ. Which better describes a typical summer day in New York in 1973?

With 116 days of data, hand calculation would be tedious but follows exactly the same steps as Example 2.3. We let R do it. Ozone is missing on 37 days, so we need na.rm = TRUE.

R
oz <- airquality$Ozone
sum(!is.na(oz))                # number of days with a reading
mean(oz, na.rm = TRUE)
median(oz, na.rm = TRUE)
output
[1] 116
[1] 42.12931
[1] 31.5

The mean is 42.1 parts per billion and the median 31.5. To see why they differ, mark both on a histogram:

R
ggplot(airquality, aes(x = Ozone)) +
  geom_histogram(binwidth = 10, boundary = 0, colour = "white", na.rm = TRUE) +
  geom_vline(xintercept = mean(oz, na.rm = TRUE)) +
  geom_vline(xintercept = median(oz, na.rm = TRUE), linetype = "dashed") +
  labs(x = "ozone (ppb)", y = "number of days")
Histogram of 116 daily ozone readings in parts per billion, with a tall peak between…Histogram of 116 daily ozone readings in parts per billion, with a tall peak between about 10 and 40 and a long right tail reaching 168. A solid vertical line marks the mean at 42.1, and a dashed line marks the median at 31.5, to the left of the mean. 0 10 20 0 50 100 150 ozone (ppb) number of days

The distribution is right-skewed. Half of all days had ozone at or below 31.5, but a handful of very high days (up to 168) sit far out on the right. In the balance-point picture, they are at the end of a long lever, and they pull the mean (solid line) to the right of the median (dashed line).

For a "typical day", the median is the better description: about half of days are below it and half above, whereas most days (72 of the 116, about 62%) are below the mean. But the mean has its uses. Total exposure over the summer is (number of days) × (mean), so a public-health official estimating total exposure needs the mean. Which centre is "right" depends on the question.

The mode

Definition: Mode

The mode of a dataset is its most frequent value. A dataset can have more than one mode (if several values tie for most frequent), and for a numerical variable recorded with many decimal places, every value may occur only once, so the mode is useful mainly for categorical data and for discrete counts. For a histogram, we speak of the modal bin or of peaks (Section 2.1).

For the insect counts in Example 2.3(b), the value 14 occurs three times and nothing else occurs more than twice, so the mode is 14. For glass type in fgl, the counts are WinF 70, WinNF 76, Veh 17, Con 13, Tabl 9 and Head 29, so the modal type is WinNF (building window, non-float). The mode is the only measure of centre that makes sense for a nominal variable: there is no "average glass type" and no "middle glass type". Base R has no function for the mode, but table() does the work:

R
table(sprayA)                       # how often each count occurs
names(which.max(table(sprayA)))     # the most frequent value
table(MASS::fgl$type)
output
sprayA
 7 10 12 13 14 17 20 23 
 1  2  1  1  3  1  2  1 
[1] "14"

 WinF WinNF   Veh   Con  Tabl  Head 
   70    76    17    13     9    29 

Resistance and the trimmed mean

Definition: Resistant Summary

A summary is resistant (or robust) if changing a few observations, even to wildly wrong values, can change it only a little. The median is resistant; the mean is not.

To see the difference, imagine changing the largest value in a dataset to a billion. The mean shoots up towards a billion. The median doesn't move at all, because the largest value is still the largest, and the middle of the sorted list is unchanged.

Is there a compromise between the two? Yes: throw away the most extreme values at both ends, and average what is left.

Definition: Trimmed Mean

The α-trimmed mean, for 0≤α<0.5, is computed in three steps.

  1. Sort the data.
  2. Let k=⌊nα⌋ (that is, nα rounded down to a whole number). Delete the k smallest and the k largest observations.
  3. Average the n−2k observations that remain.

In R: mean(x, trim = alpha). A "10% trimmed mean" has α=0.1.

Trimmed means are used where outliers are a real worry and the mean is still wanted: Olympic diving and gymnastics drop the highest and lowest judges' scores before averaging, which is a trimmed mean that stops one biased judge deciding a medal.

Example 2.5: A Typo in the Lab Notebook

A toxicologist records five blood alcohol readings (g/dL) from repeated tests of one sample: 0.081, 0.079, 0.083, 0.080, and 0.82, where the last should have been 0.082. Compute the mean, the median and the 20% trimmed mean, by hand and in R.

Mean. The five readings add to 0.081+0.079+0.083+0.080+0.82=1.143, so x‾=1.1435=0.2286.

Median. Sorted: 0.079, 0.080, 0.081, 0.083, 0.82. The middle (third) value is 0.081.

20% trimmed mean. Here nα=5×0.2=1, so k=1: delete one value from each end of the sorted list (0.079 and 0.82) and average the remaining three: 0.080+0.081+0.0833=0.2443≈0.0813.

R
bac <- c(0.081, 0.079, 0.083, 0.080, 0.82)
mean(bac)
median(bac)
mean(bac, trim = 0.2)    # drops the lowest and highest 20%: one value each
output
[1] 0.2286
[1] 0.081
[1] 0.08133333

One misplaced decimal point drags the mean to 0.229, almost three times the real level, and far above the legal driving limit of 0.08. The median (0.081) and trimmed mean (0.0813) barely notice. This is why it's wise to compute both the mean and the median: if they disagree badly, look for skewness or errors. (And never simply delete an observation because it is inconvenient: find out why it is unusual. Here, the lab notebook showed a transcription error.)

A picture makes the damage plain:

R
ggplot(data.frame(bac, y = c(-0.3, 0.3, 0, -0.15, 0.15)), aes(x = bac, y = y)) +
  geom_point(size = 3, alpha = 0.8) +
  geom_vline(xintercept = mean(bac)) +
  geom_vline(xintercept = c(median(bac), mean(bac, trim = 0.2)), linetype = "dashed") +
  annotate("text", x = mean(bac) + 0.01, y = -0.8, label = "mean", hjust = 0, size = 3.8) +
  annotate("text", x = median(bac) + 0.01, y = 0.8, label = "median and\ntrimmed mean", hjust = 0, size = 3.8) +
  scale_y_continuous(NULL, breaks = NULL, limits = c(-1, 1)) +
  labs(x = "blood alcohol reading (g/dL)")
Dot plot of five blood alcohol readings on a scale running up to 0.85Dot plot of five blood alcohol readings on a scale running up to 0.85. Four readings cluster at about 0.08 and one sits far to the right at 0.82. A solid line marks the mean at 0.229, in the empty space between the cluster and the outlier, while dashed lines for the median and trimmed mean sit inside the cluster. mean median and trimmed mean 0.2 0.4 0.6 0.8 blood alcohol reading (g/dL)

The mean lands in empty space, where no reading is: it describes nothing that happened. That's a good visual test for any summary: does it sit where the data are?

The trimmed mean is not one summary but a whole family, with the mean and the median at its two ends.

So choosing a trimming fraction is choosing how much to trust the extremes. The widget below makes the journey visible on the ozone data.

From the mean to the median: the trimmed mean

The dots are the 116 days of New York ozone readings in airquality (ppb), sorted along the line. The trimmed mean removes the same number of days from each end and averages the rest. Slide the trimming percentage from 0% to 50%: removed days fade out, and the trimmed mean travels from the mean to the median. The bottom panel traces its whole journey.

TopTop: dot plot of 116 ozone readings with trimmed values faded and the mean, median and trimmed mean marked. Bottom: the trimmed mean plotted against the percentage trimmed from each end.

Choosing a measure of centre

measure what it is strengths weaknesses
mean balance point uses every value; easy algebra; links to totals (total = n× mean); the basis of most later methods pulled by outliers and long tails; can describe a value nobody has (Old Faithful)
median middle value resistant to outliers; a natural "typical" value for skewed data; half above, half below ignores how far out the extremes are; harder to work with mathematically
trimmed mean mean of the middle a tunable compromise: resistant, yet uses more of the data than the median the trimming fraction is a choice someone has to make and justify
mode most common value the only option for nominal categories; the best "single bet" may not exist or may not be unique; unstable for continuous data

Why the mean and median are "best" guesses

There is a deeper way to think about centre, and it connects directly to Chapter 1's airline. Suppose you must summarize the data with a single number c, and every data value charges you a penalty depending on how far it is from c. Which c makes the total penalty smallest? The answer depends on the penalty rule. Try it before reading the theorem.

One number to stand for all the data: which guess costs least?

The dots are the numbers of burglaries reported in a police precinct in six weeks: 3, 5, 4, 7, 2, 3. You must summarize them with a single guess c (the orange line), and every dot charges you a penalty for being away from your guess. The number above each dot is its penalty. The bottom panel adds up the penalties for every possible guess. Your job: slide c to make the total penalty as small as possible. Then change the penalty rule and see whether the best guess moves.

TopTop: the data as dots on a number line with the guess marked and each dot's penalty written above it. Bottom: total penalty plotted against the guess, with the lowest point marked.

Theorem: Mean, Median and Mode as Best Guesses

For observations x1,…,xn:

  1. The total squared distance ∑i=1n(xi−c)2 is smallest when c=x‾, the mean.
  2. The total absolute distance ∑i=1n|xi−c| is smallest when c is a median.
  3. The number of misses, #{i:xi≠c}, is smallest when c is a mode.
  4. The deviations from the mean always add to zero: ∑i=1n(xi−x‾)=0.

Part 4 (needed for part 1). Split the sum and use ∑ixi=nx‾: ∑i=1n(xi−x‾)=∑i=1nxi−nx‾=nx‾−nx‾=0.

Part 1. Let g(c)=∑i(xi−c)2. Differentiate with respect to c, using the chain rule on each term: g′(c)=∑i=1n2(xi−c)(−1)=−2(∑i=1nxi−nc)=−2n(x‾−c). This is zero only at c=x‾. Since g″(c)=2n>0, the graph of g is a parabola opening upwards, so c=x‾ is its minimum.

A proof without calculus. Write xi−c=(xi−x‾)+(x‾−c) and expand the square: ∑i=1n(xi−c)2=∑i=1n(xi−x‾)2+2(x‾−c)∑i=1n(xi−x‾)+n(x‾−c)2=∑i=1n(xi−x‾)2+n(x‾−c)2.∑i=1n(xi−c)2=∑i=1n(xi−x‾)2+2(x‾−c)∑i=1n(xi−x‾)+n(x‾−c)2=∑i=1n(xi−x‾)2+n(x‾−c)2. The middle term vanished by part 4. The first term doesn't depend on c, and the second is never negative and is zero exactly when c=x‾.

Part 2. Imagine sliding c to the right by a tiny amount δ, not passing any data point. Every observation to the right of c gets δ closer, and every observation at or to the left of c gets δ further away. Write L for the number of observations at or to the left of c, and R for the number to the right. Then the total absolute distance changes by δ×(L−R). If more observations lie to the right of c (R>L), this is negative and moving right helps; if more lie to the left, moving left helps. As c moves right, the bracket can only increase, so the total first decreases, then (possibly) stays flat, then increases. The minimum is reached where neither direction helps, which is exactly when at most half the observations lie strictly on either side of c: the middle value when n is odd, and any point between the two middle values (including their average) when n is even. These are the medians.

Part 3. If c is not one of the data values, every observation is a miss. If c equals a value that occurs m times, the number of misses is n−m. This is smallest when m is as large as possible, that is, when c is the most frequent value. ◼∎

So the mean is the best single guess if big errors are especially costly (squared penalty: an error of 10 costs 100 times as much as an error of 1), the median is the best guess if every unit of error costs the same (absolute penalty), and the mode is the best guess if only an exact hit counts. This is the same idea as Chapter 1's airline: the best prediction depends on the cost of being wrong.

Interlude (Optional): Loss Functions: The Hidden Cost Behind Every Guess

What is a loss function? A loss function L(y,c) is a rule that says how bad it is to guess c when the truth turns out to be y. It is zero for a perfect guess and grows as the guess gets worse. The penalties in the widget above are three loss functions:

loss function formula what it punishes best guess
squared error (y−c)2 big misses, very heavily the mean
absolute error |y−c| every unit of error equally the median
zero–one 0 if c=y, else 1 being wrong at all, however close the mode

So the three familiar measures of centre are not three unrelated recipes. Each is the answer to the same question, "which single guess has the smallest total loss?", for a different loss function.

You use loss functions all the time. You just don't write them down.

  • Leaving for a train. Arriving 10 minutes early costs you 10 minutes of waiting; arriving 1 minute late costs you the train. Your loss is lopsided, so you don't aim for the average journey time: you leave early, aiming for a high percentile of the journey time instead. (With a lopsided loss, the best guess is a quantile, which we define in Section 2.3.)
  • Guessing how many people will come to a party. If you'll be embarrassed by running out of food but don't mind leftovers, you over-cater, again a lopsided loss.
  • A multiple-choice exam. A nearly right answer scores the same as a wildly wrong one. That's zero–one loss, so the best strategy is to pick the single most likely option (the mode), not some "average" of the options.
  • A weather forecast. Squared error punishes a forecaster who is off by 10 degrees a hundred times as much as one who is off by 1, so forecasters judged this way avoid big misses above all.

Different loss functions disagree because they care about different things. Squared loss is terrified of large errors, which is why it is dragged around by outliers: it will move the guess a long way to avoid one huge miss. Absolute loss is calmer: one far-away point costs only its distance, so it can't drag the median far. Zero–one loss doesn't care about distance at all.

Machine learning is loss minimization. When a machine-learning model is "trained", what actually happens is that a computer searches for the settings that make the average loss over a training dataset as small as possible.

  • A model predicting house prices is usually trained with squared loss, so it learns something like a mean price for houses with given features.
  • A model that must not be swayed by a few absurd listings might use absolute loss instead, learning a median.
  • A spam filter or image classifier is trained with a loss that rewards putting high probability on the correct category (called cross-entropy, related to the entropy in Section 2.6).
  • A model forecasting electricity demand, where a blackout is far worse than spare capacity, uses a lopsided "quantile loss".

Choosing the loss is choosing what the model cares about, and that is a human decision, not a mathematical one. Chapter 8 returns to squared-error loss when it judges estimators by their mean squared error.

Why it matters: whenever someone reports "the best estimate", ask "best according to which loss?".

Bayesian Inference: The Same Tools Describe Beliefs

In Bayesian statistics, what you know about an unknown quantity, say the true blood alcohol level, is itself described by a distribution: the posterior. To report a single best guess, Bayesians use exactly the tools of this section: the posterior mean (best under squared-error loss), the posterior median (best under absolute-error loss), or the posterior mode (best under zero–one loss), with the theorem above telling them which to use. And to report uncertainty, they describe the posterior's spread.

Check Yourself

Find the median of the six times 14, 9, 11, 22, 12, 10 minutes.

House prices in a neighbourhood: most around $400,000, a few mansions above $5 million. Which is larger?

Using the 12 insect counts of spray A (sorted: 7, 10, 10, 12, 13, 14, 14, 14, 17, 20, 20, 23), compute the 10% trimmed mean.

You must guess a single number for tomorrow's count of emergency calls. You lose $1 for every call your guess is off by, in either direction. Which guess minimizes your total loss over past days?

Think About It: Which Centre Would You Report?

For each situation, decide whether you would report the mean, the median or the mode, and explain why in terms of what the number will be used for. (a) A city budgeting for total overtime pay. (b) A news report on "typical" rent. (c) A shoe shop deciding which size to stock most of. (d) A prosecutor describing the "typical" sentence for a crime, when a few sentences were extremely long.

(a) The mean: total = number of employees × mean, so a budget needs it. (b) The median: rents are right-skewed, and the median is what a typical renter pays. (c) The mode: the shop wants the single most common size. (d) The median, because a few extreme sentences would pull the mean up and misrepresent the usual outcome; reporting the mean here could mislead a jury. The "right" centre depends on the loss you care about, which is the idea behind Section 2.2's theorem.

Key Takeaways

  • Mean x‾ = balance point; median = middle of the sorted data (average the two middle values when n is even); mode = most common value.
  • For right-skewed data, usually mean > median. Report the one that answers your question.
  • The median and trimmed mean are resistant to extreme values; the mean is not. Trimmed means run from the mean (0%) to the median (50%).
  • The mean minimizes squared loss, the median absolute loss, the mode zero–one loss. The best guess depends on the cost of being wrong.

2.3 Spread: how much do the data vary?

Two drug-testing instruments both give the right answer on average. One gives readings within 1% of the truth; the other is sometimes 20% off. Their means are identical; only their spread tells them apart. In science, medicine and forensics, spread is often the more important number.

The range

Definition: Range

The range of a dataset is the largest observation minus the smallest: x(n)−x(1).

For the toxin concentrations of Example 2.3, the range is 15.3−9.8=5.5 ng/mL. The range is easy to compute and to explain, but it depends on only two observations, the most extreme ones, so a single outlier changes it completely, and it tends to grow as you collect more data. (R's range(x) returns the minimum and maximum; diff(range(x)) gives their difference.)

Variance and standard deviation

A better measure of spread uses every observation: how far, typically, is an observation from the mean? The distances from the mean, xi−x‾, are called deviations. We can't just average them, because they always add to zero (part 4 of the theorem in Section 2.2): the positive and negative ones cancel. So we square them first, making them all positive, average the squares, and then take a square root at the end to get back to the original units.

Definition: Sample Variance and Standard Deviation

The sample variance of x1,…,xn is s2=1n−1∑i=1n(xi−x‾)2. The sample standard deviation is its square root, s=s2. It is measured in the same units as the data. In R: var(x) and sd(x).

Idea: Algorithm: Standard Deviation by Hand

  1. Compute the mean x‾.
  2. For each observation, compute the deviation xi−x‾. (Check: they add to 0.)
  3. Square each deviation.
  4. Add up the squares.
  5. Divide by n−1. This is the variance s2.
  6. Take the square root. This is the standard deviation s.

Example 2.6: Standard Deviation by Hand ★ lecture example

Compute the variance and standard deviation of the toxin concentrations 12.1, 9.8, 15.3, 11.0 and 10.4 ng/mL by hand, then check in R.

Step 1. From Example 2.3, x‾=11.72.

Steps 2 to 4. Tabulate the deviations and their squares:

xᵢ xᵢ−x‾ (xᵢ−x‾)²
12.1 0.38 0.1444
9.8 −1.92 3.6864
15.3 3.58 12.8164
11.0 −0.72 0.5184
10.4 −1.32 1.7424
sum 0 18.908

The deviations add to 0, as they must: a good check on the arithmetic.

Steps 5 and 6. s2=18.9085−1=18.9084=4.727(ng/mL)2,s=4.727≈2.17 ng/mL.s2=18.9085−1=18.9084=4.727(ng/mL)2,s=4.727≈2.17 ng/mL.

R
conc <- c(12.1, 9.8, 15.3, 11.0, 10.4)
conc - mean(conc)                   # the deviations
sum((conc - mean(conc))^2)          # sum of squared deviations
var(conc)
sd(conc)
output
[1]  0.38 -1.92  3.58 -0.72 -1.32
[1] 18.908
[1] 4.727
[1] 2.174167

A picture shows what the standard deviation is summarizing. Each vertical segment below is one deviation:

R
d <- data.frame(sample = 1:5, conc = conc)
ggplot(d, aes(x = sample, y = conc)) +
  geom_hline(yintercept = mean(conc), linetype = "dashed") +
  geom_segment(aes(xend = sample, yend = mean(conc)), colour = "orange") +
  geom_point(size = 3) +
  labs(x = "sample", y = "toxin (ng/mL)")
Dot plot of five toxin concentrations against sample number, with a horizontal line at…Dot plot of five toxin concentrations against sample number, with a horizontal line at the mean of 11.72. A vertical segment joins each point to the mean line. The longest segment belongs to 15.3, above the line; the other segments are shorter. Two points lie above the line and three below. 10 12 14 1 2 3 4 5 sample toxin (ng/mL)

The standard deviation is roughly a "typical length" of these segments: a typical sample is about 2.2 ng/mL from the average. Squaring gives the longest segment (3.58, for 15.3) a big say: it contributes 12.8 of the total 18.9. Notice also that the variance is in squared units, (ng/mL)², which are hard to interpret; that's why we usually report the standard deviation.

See the deviations

These are the five toxin concentrations of Example 2.6. Each horizontal line is a deviation, the distance from an observation to the mean (the vertical line). The bars below show the squared deviations, which the variance averages. Move the largest observation and watch what happens: the squared deviation of a far-out value grows very fast, so the standard deviation is pulled up much more than the median and the MAD.

TopTop: five observations on a number line with the mean marked and a horizontal line from each observation to the mean. Bottom: a bar for each observation's squared deviation.

Why divide by n−1 rather than n? The deviations are measured from x‾, which was computed from the same data and therefore sits right in the middle of them. Theorem part 1 says x‾ is the point that makes the sum of squared deviations as small as possible, so measuring from x‾ gives a slightly smaller sum than measuring from the true population mean would. Dividing by n−1 instead of n inflates the answer just enough to correct for this on average. Chapter 8 makes this precise: s2 is an unbiased estimator of the population variance. For large n the difference hardly matters.

Reading a standard deviation

How should you read a standard deviation? For many datasets, especially roughly symmetric, single-peaked ones, the following rule of thumb holds.

Idea: The 68–95 Rule of Thumb

For roughly symmetric, bell-shaped data, about 68% of observations lie within one standard deviation of the mean (between x‾−s and x‾+s), and about 95% within two (between x‾−2s and x‾+2s). (Chapter 5 explains where these numbers come from: the Gaussian distribution.)

Here is the rule at work on the birth weights of Chapter 1. The darker band is one standard deviation either side of the mean; the lighter band, two.

R
bw <- MASS::birthwt$bwt; m <- mean(bw); s <- sd(bw)
c(within_1_sd = mean(abs(bw - m) <= s), within_2_sd = mean(abs(bw - m) <= 2 * s))
ggplot(data.frame(bw), aes(bw)) +
  annotate("rect", xmin = m - 2 * s, xmax = m + 2 * s, ymin = -Inf, ymax = Inf, fill = "steelblue", alpha = 0.12) +
  annotate("rect", xmin = m - s, xmax = m + s, ymin = -Inf, ymax = Inf, fill = "steelblue", alpha = 0.22) +
  geom_histogram(binwidth = 250, boundary = 0, colour = "white") +
  geom_vline(xintercept = m) +
  labs(x = "birth weight (g)", y = "number of babies")
output
within_1_sd within_2_sd 
  0.6772487   0.9629630 
Histogram of the 189 birth weights in grams, roughly bell-shaped and centred near 2,945Histogram of the 189 birth weights in grams, roughly bell-shaped and centred near 2,945. A darker shaded band marks one standard deviation either side of the mean, from 2,215 to 3,674 g, and a lighter band two standard deviations, from 1,486 to 4,403 g. Almost all the babies fall inside the lighter band. 0 10 20 1000 2000 3000 4000 5000 birth weight (g) number of babies

For the 189 birth weights in birthwt (mean 2,945 g, standard deviation 729 g), one standard deviation either side of the mean is 2,215 g to 3,674 g, and 67.7% of babies fall in it; two standard deviations either side is 1,486 g to 4,403 g, and 96.3% fall in it. Very close to the rule. But for skewed or two-peaked data the rule can fail badly. The next result holds for every dataset, whatever its shape.

Theorem: Chebyshev's Inequality for Data

For any dataset and any k>1, the fraction of observations more than k standard deviations from the mean is less than 1/k2. In particular, more than 75% of any dataset lies within 2 standard deviations of its mean, and more than 8/9 (about 88.9%) within 3.

Suppose m of the n observations satisfy |xi−x‾|>ks. Each of them contributes more than k2s2 to the sum of squared deviations, and the other terms are non-negative, so (n−1)s2=∑i=1n(xi−x‾)2>mk2s2. Dividing both sides by nk2s2 gives mn<n−1n⋅1k2<1k2. (If s=0 all observations equal the mean and there is nothing to prove.) ◼∎

Chebyshev's guarantee is weak (75% instead of the rule of thumb's 95%), but it never fails. That's the trade-off between assuming something about the shape and assuming nothing.

Quantiles and quartiles

The standard deviation squares deviations, so it is even less resistant than the mean: one extreme value can inflate it enormously. Resistant measures of spread are built from quantiles instead.

Definition: Quantiles, Percentiles and Quartiles

For 0<p<1, the p-quantile (or 100pth percentile) of a dataset is a value with roughly a fraction p of the observations below it and 1−p above it. The first quartile Q1 is the 0.25-quantile, the median is the 0.5-quantile, and the third quartile Q3 is the 0.75-quantile.

For small datasets "roughly" needs a precise rule, and different books and programs use slightly different ones. These notes use R's default rule:

  1. Sort the data: x(1)≤x(2)≤⋯≤x(n).
  2. Compute the position h=1+(n−1)p.
  3. If h is a whole number, the quantile is x(h). Otherwise, write h=j+f with j a whole number and 0<f<1, and move a fraction f of the way from x(j) to x(j+1): Q(p)=x(j)+f(x(j+1)−x(j)).

In R: quantile(x, p). With p=0.5 this rule always gives the median.

The rule spreads the n sorted values evenly from "0% of the way along" (the minimum, position 1) to "100% of the way along" (the maximum, position n). The 25% point is then a quarter of the way along, at position 1+(n−1)/4, and if that falls between two observations we interpolate.

Definition: IQR and MAD

  • The interquartile range is IQR=Q3−Q1: the width of the middle half of the data. In R: IQR(x).
  • The median absolute deviation (MAD) is the median of the distances from the median, |xi−x̃|. In R: mad(x, constant = 1).

R's plain mad(x) multiplies the MAD by 1.4826. That constant makes the MAD comparable to the standard deviation for bell-shaped data, so that the two can be compared directly. Always say which version you are reporting.

Example 2.7: Quartiles, IQR and MAD by Hand ★ lecture example

For the 12 insect counts of spray A (Example 2.3), compute the quartiles, IQR and MAD by hand, and check in R.

Sort. 7, 10, 10, 12, 13, 14, 14, 14, 17, 20, 20, 23, so x(1)=7, x(2)=10, and so on up to x(12)=23.

First quartile. The position is h=1+(12−1)(0.25)=1+2.75=3.75. So j=3 and f=0.75: go three-quarters of the way from x(3)=10 to x(4)=12: Q1=10+0.75×(12−10)=10+1.5=11.5.

Median. h=1+11×0.5=6.5: halfway between x(6)=14 and x(7)=14, so x̃=14, as in Example 2.3.

Third quartile. h=1+11×0.75=9.25. So j=9 and f=0.25: a quarter of the way from x(9)=17 to x(10)=20: Q3=17+0.25×(20−17)=17+0.75=17.75.

IQR. 17.75−11.5=6.25 insects. The middle half of the plots had counts spread over an interval about 6 insects wide.

MAD. The distances from the median 14 are

xᵢ 7 10 10 12 13 14
|xi−14| 7 4 4 2 1 0
xi 14 14 17 20 20 23
|xi−14| 0 0 3 6 6 9

Sorted, the distances are 0, 0, 0, 1, 2, 3, 4, 4, 6, 6, 7, 9; the median of these 12 is (3+4)/2=3.5. So MAD = 3.5 insects.

R
quantile(sprayA)               # min, Q1, median, Q3, max
IQR(sprayA)
mad(sprayA, constant = 1)      # the plain MAD
mad(sprayA)                    # R's default: 1.4826 x MAD
sd(sprayA)                     # for comparison
output
   0%   25%   50%   75%  100% 
 7.00 11.50 14.00 17.75 23.00 
[1] 6.25
[1] 3.5
[1] 5.1891
[1] 4.719399

All the hand calculations match. Notice that the rescaled MAD (5.19) and the standard deviation (4.72) are similar, as they should be for data without extreme outliers.

Watch Out: Different Software, Different Quartiles

Some textbooks find Q1 as "the median of the lower half of the data". For spray A that gives 11 rather than 11.5, and R's fivenum() and base-R boxplot() use a similar rule (Tukey's hinges). Neither answer is wrong; they are different conventions, and for large datasets they agree closely. In this course we use R's quantile() rule, and you should state which rule you used if you compute quartiles by hand.

Example 2.8: Michelson Measures the Speed of Light ★ lecture example

In 1879 the young physicist Albert Michelson measured the speed of light at the US Naval Academy, using rotating mirrors. R's morley dataset holds 100 of his measurements, in 5 experiments of 20 runs each, recorded as the speed in km/s minus 299,000. Today the speed of light in a vacuum is fixed by definition at exactly 299,792.458 km/s. Michelson measured it in air, where light travels slightly slower; adjusted for air, the true value for his measurements is about 299,734.5 km/s (S. Stigler, Annals of Statistics, 1977).

  1. Compute the mean, median, standard deviation and IQR of Michelson's measurements.
  2. How far is his average from the true value, compared with the spread of his measurements?
  3. Compare the five experiments with boxplots (Section 2.4 explains how to read them). What do you notice?
R
speed <- morley$Speed + 299000        # undo the coding: km/s
mean(speed); median(speed)
sd(speed); IQR(speed)
mean(speed) - 299734.5                # how far off is the average (in air)?
output
[1] 299852.4
[1] 299850
[1] 79.01055
[1] 85
[1] 117.9
  1. Mean 299,852 km/s, median 299,850 km/s, standard deviation 79 km/s, IQR 85 km/s. Mean and median agree closely, so the 100 measurements, taken together, are roughly symmetric. (Experiment 1 on its own was left-skewed, as we saw in Example 2.2: shapes can differ between parts of a dataset.)

  2. The average is 118 km/s too high, about one and a half standard deviations: 11879≈1.5. That might not sound like much, but averaging 100 measurements cancels out most of the random scatter. Chapter 7 shows that the uncertainty in an average of 100 independent measurements is about a tenth of a single measurement's, here about 8 km/s. A 118 km/s miss is far bigger than chance alone can explain. Something pushed all the measurements up. Statisticians distinguish random error (scatter, which averaging reduces) from systematic error or bias (a consistent push in one direction, which averaging can never remove).

R
ggplot(morley, aes(x = factor(Expt), y = Speed + 299000)) +
  geom_boxplot() +
  geom_hline(yintercept = 299734.5, linetype = "dashed") +
  labs(x = "experiment", y = "speed of light (km/s)")
Boxplots of Michelson's speed of light measurements for each of five experiments of 20…Boxplots of Michelson's speed of light measurements for each of five experiments of 20 runs. The medians range from about 299,810 to 299,940 km/s, with experiment 1 highest and most spread out. A dashed horizontal line at the true value in air, about 299,735 km/s, lies below the whole box of every experiment. 299600 299700 299800 299900 300000 1 2 3 4 5 experiment speed of light (km/s)
  1. The experiments differ: experiment 1 is noticeably higher and more variable than the others. And the true value (dashed line) sits below the middle half of every experiment. The 100 runs are not independent repetitions of one identical process (conditions changed between experiments), a reminder of Chapter 1's warning about IID data. Michelson kept improving his apparatus for decades, and in 1907 became the first American to win a Nobel Prize in science, for his precision optical instruments.

Choosing a measure of spread

measure what it is strengths weaknesses
range max − min simplest possible; shows the full extent of the data uses only two values; wrecked by one outlier; grows with sample size
standard deviation typical distance from the mean uses every value; same units as data; the basis of most later methods (Chapters 5–9); 68–95 rule for bell shapes not resistant: one outlier can inflate it a lot; less meaningful for strongly skewed data
variance s2 adds up nicely for sums of independent quantities (Chapter 6) squared units, hard to interpret directly
IQR width of the middle half resistant; pairs naturally with the median; drives the boxplot ignores the outer half of the data entirely; depends on the quantile rule for small n
MAD median distance from the median the most resistant of all less familiar; needs care with the 1.4826 scaling

A good rule of thumb: report the mean with the standard deviation for roughly symmetric data, and the median with the IQR for skewed data or data with outliers.

Check Yourself

Two labs measure the same reference sample many times. Lab A: mean 5.00, standard deviation 0.40. Lab B: mean 5.30, standard deviation 0.05. The true value is 5.00. Which statement is right?

Without knowing anything about the shape of a dataset, what fraction of observations within 2 standard deviations of the mean does Chebyshev's inequality guarantee, at minimum? (Give a decimal.)

Using R's rule, find Q1 for the six times 9, 10, 11, 12, 14, 22.

A dataset of 50 reaction times has one value recorded in milliseconds instead of seconds (so it's 1,000 times too big). Which summary of spread is affected least?

Think About It: Spread as the Price of a Prediction

You must predict tomorrow's high temperature in two cities, one coastal and one inland, which have the same average temperature but standard deviations of 3°F and 9°F. Your forecast is the mean in both cases. How far off do you expect to be in each city? What does this say about the relationship between spread and prediction error?

If you always predict the mean, your typical error is about one standard deviation: around 3°F at the coast and 9°F inland. So the standard deviation of the data is the typical size of the error you make when you predict with the mean. That is the deepest reason spread matters: it measures how predictable something is. A big spread doesn't mean the data are wrong; it means a single number can't tell you much about the next case, and you should look for other information (season, weather fronts) that explains some of the variation.

History: Who Named the Standard Deviation, and Should We Rename It?

The term standard deviation was coined by the English statistician Karl Pearson in a lecture in 1893, published in 1894; he also introduced the word histogram. The word variance came later, from Ronald Fisher, in a 1918 paper on how traits are passed from parents to children. Both men were brilliant mathematicians, and both were committed eugenicists. In 1911 Pearson became the first Galton Professor of Eugenics at University College London, and Fisher held the same chair from 1933. Much of their work on heredity was driven by eugenic aims: encouraging some groups of people to have more children and discouraging others. The history boxes in Sections 4.6 and 5.3 tell more of the story.

In Bernoulli's Fallacy (2021), the mathematician Aubrey Clayton argues that statistics should rethink some of the words it inherited from this period, partly because of where they came from and partly because they mislead. "Deviation" sounds judgmental, as if differing from the average were a fault. He suggests calling the standard deviation the uncertainty (and its reciprocal the precision), and calling the variance simply the second central moment. He makes similar proposals for "random variable", "correlation", "regression" and "statistically significant", which later chapters mention as they arise.

These notes keep the standard names "standard deviation" and "variance", because renaming them causes real problems:

  • every textbook, scientific paper and piece of software you will meet uses them (R's functions are sd() and var()), and a statistically literate reader has to recognize them;
  • Clayton's replacements already mean other things: "uncertainty" is used for the margin of error on a measurement (Chapter 5) and for interval estimates (Chapter 8), so using it for a spread of data would cause confusion.

Still, the words are not neutral descriptions handed down by nature. Particular people chose them for particular purposes. A deviation from the mean is just a difference, never a defect.

Key Takeaways

  • Range = max − min: simple but fragile.
  • Variance s2 averages squared deviations (dividing by n−1); the standard deviation s is its square root, in the data's units.
  • For bell-shaped data, about 68% / 95% lie within 1 / 2 SDs of the mean. Chebyshev: more than 1−1/k2 within k SDs, for any data.
  • Quantiles by R's rule: position h=1+(n−1)p, then interpolate. IQR and MAD are resistant measures of spread.
  • Random error scatters measurements; systematic error (bias) shifts them all. Averaging reduces only the first.

Lecture 4 — Boxplots, honest pictures and Simpson's paradox

2.4 Position, outliers and boxplots

Is a birth weight of 2,500 g unusual? Is a glass fragment's refractive index consistent with window glass? Questions like these ask about one observation's position within a distribution. Quantiles (Section 2.3) answer one version: a baby "on the 10th percentile" for weight is lighter than 90% of babies of the same age. z-scores answer another.

z-scores

Definition: Standardized Value (z-Score)

The z-score of an observation x is its distance from the mean in units of standard deviations: z=x−x‾s. A z-score of 2 means "two standard deviations above the mean"; −1.5 means "one and a half standard deviations below".

z-scores let us compare observations measured on different scales: is a student who scored 85 on an exam with mean 70 and SD 10 (z=1.5) further above average than one who scored 620 on an exam with mean 500 and SD 100 (z=1.2)? Yes. And z-scores don't depend on the units: converting grams to pounds changes x, x‾ and s by the same factor, which cancels. Here is the general fact.

Theorem: Changing Units

If every observation is transformed to yi=a+bxi (for constants a and b), then y‾=a+bx‾andsy=|b|sx. In words: adding a constant shifts the centre but not the spread; multiplying by b multiplies both by b (the spread by |b|, since spread can't be negative).

The mean. Using the sum rules from Section 0.4, y‾=1n∑i=1n(a+bxi)=1n(na+b∑i=1nxi)=a+bx‾.

The standard deviation. Each deviation becomes yi−y‾=(a+bxi)−(a+bx‾)=b(xi−x‾), so the constant a cancels. Squaring and adding, ∑i=1n(yi−y‾)2=b2∑i=1n(xi−x‾)2. Divide by n−1 to get sy2=b2sx2, and take square roots: sy=|b|sx. ◼∎

For example, converting Celsius to Fahrenheit (F=32+1.8C) multiplies the mean by 1.8 and then adds 32, but only multiplies the standard deviation by 1.8: shifting every temperature up by 32 degrees doesn't make them any more spread out. The theorem also shows that z-scores always have mean 0 and standard deviation 1: the z-score is y=a+bx with b=1/s and a=−x‾/s, so its mean is −x‾/s+x‾/s=0 and its SD is s/s=1.

Example 2.9: Is This Glass from a Window? ★ lecture example

A glass fragment is found in the jacket of a suspect in a burglary where a window was broken. Its refractive index, in the coding of the fgl data (Example 1.3), is 6.0. Using the 70 fragments of building window glass made by the float process (type == "WinF") as a reference, compute the fragment's z-score and percentile. What can and can't you conclude?

R
library(MASS)
winf <- fgl$RI[fgl$type == "WinF"]
c(mean = mean(winf), sd = sd(winf), n = length(winf))
(6.0 - mean(winf)) / sd(winf)       # z-score of the jacket fragment
mean(winf >= 6.0)                    # fraction of window fragments at least this high
output
      mean         sd          n 
 0.7182857  2.2680969 70.0000000 
[1] 2.328699
[1] 0.01428571

The z-score is z=6.0−0.7182.268=5.2822.268≈2.33, so the fragment's refractive index is 2.3 standard deviations above the average for float window glass. Only 1 of the 70 reference fragments (about 1.4%) is as high, so the fragment sits at roughly the 99th percentile of the reference distribution.

So the fragment is unusual for float window glass, though not impossible. What we can't conclude: whether it came from this window. That needs a comparison with glass from the broken window itself, not with window glass in general, and it needs the reference distribution to be representative. Forensic glass examiners compare the measured value of the recovered fragment with fragments from the scene and ask how often such a match would occur by chance, which is the kind of question Chapter 3's probability and Chapter 9's tests answer.

A histogram of the reference fragments shows where the jacket fragment falls:

R
ggplot(data.frame(RI = winf), aes(RI)) +
  geom_histogram(binwidth = 1, boundary = 0, colour = "white") +
  geom_vline(xintercept = 6.0, linetype = "dashed") +
  labs(x = "refractive index (coded), float window glass", y = "number of fragments")
Histogram of the refractive index of 70 float window glass fragments, coded as in the fgl…Histogram of the refractive index of 70 float window glass fragments, coded as in the fgl data. Values run from about -6 to 9: a tall peak just below 0, a smaller cluster between 3 and 5, one low value near -5.9 and one fragment near 8.7. A dashed vertical line marks the jacket fragment at 6.0, in the far right tail. 0 10 20 30 -5 0 5 refractive index (coded), float window glass number of fragments

Prediction and inference. As a prediction question ("if I pick a float-window fragment at random, how likely is a value this high?") the answer is about 1%. The inference question ("did this fragment come from that window?") is different, and needs the comparison with the scene's glass that forensic examiners actually make.

Outliers

Definition: The 1.5 × IQR Rule

An observation is flagged as a possible outlier if it lies more than 1.5×IQR below Q1 or above Q3. The values lower fence=Q1−1.5IQR,upper fence=Q3+1.5IQR are called the fences.

Why 1.5? It's a convention, chosen by John Tukey because it works well in practice: for bell-shaped data, it flags fewer than 1 observation in 100, so a flagged point is genuinely unusual, while still catching real outliers.

An outlier isn't automatically a mistake. It may be a data-entry error (Example 2.5), a measurement under unusual conditions, or the most interesting observation in the dataset. The rule only says: look at this one.

Boxplots

A boxplot (or box-and-whisker plot) draws the five-number summary and the outliers in one compact picture.

Definition: Five-Number Summary and Boxplot

The five-number summary of a dataset is (minimum, Q1, median, Q3, maximum).

A boxplot draws a box from Q1 to Q3 with a line at the median; whiskers from the box out to the most extreme observations that lie inside the fences; and every observation beyond the fences as an individual point.

Anatomy of a boxplot drawn horizontallyAnatomy of a boxplot drawn horizontally. A box runs from the first quartile Q1 to the third quartile Q3, with a line inside at the median. The box width is the interquartile range, IQR. Whiskers extend from the box to the most extreme observations within 1.5 times the IQR of the box. Points beyond that are drawn individually and flagged as possible outliers.smallest valuewithin the fenceQ125th percentilemedianQ375th percentilelargest valuewithin the fenceoutliers?IQR = Q3 − Q1
A boxplot shows the five-number summary and flags unusual points.

Idea: Algorithm: A Boxplot by Hand

  1. Sort the data.
  2. Median. Find the middle value; draw a line there.
  3. Quartiles. Find Q1 and Q3; draw a box from Q1 to Q3, so that the box contains the middle half of the data.
  4. Fences. Compute IQR=Q3−Q1, then the fences Q1−1.5IQR and Q3+1.5IQR. (Don't draw them; they are for checking.)
  5. Whiskers. Draw a line from the box down to the smallest observation inside the fences, and up to the largest observation inside the fences.
  6. Outliers. Plot every observation beyond a fence as a separate point.
  7. Label the axis with the variable and its units.

Work through the algorithm in the widget, one step at a time.

Build a boxplot, one step at a time

Choose a dataset, then press next step to follow the boxplot algorithm in Section 2.4. Each step adds one piece to the picture and shows the arithmetic underneath. Try doing each step on paper before pressing the button.

The sorted data on a number line, with the parts of the boxplot added step by stepThe sorted data on a number line, with the parts of the boxplot added step by step.

Example 2.10: A Boxplot by Hand ★ lecture example

Insecticide C left 0, 1, 7, 2, 3, 1, 2, 1, 3, 0, 1, 4 insects on its 12 plots. Draw a boxplot by hand, then in R.

Step 1, sort. 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 7.

Step 2, median. n=12, so average the 6th and 7th values: (1+2)/2=1.5.

Step 3, quartiles. For Q1, h=1+11×0.25=3.75: three-quarters of the way from x(3)=1 to x(4)=1, which is just 1. For Q3, h=1+11×0.75=9.25: a quarter of the way from x(9)=3 to x(10)=3, which is 3. So the box runs from 1 to 3.

Step 4, fences. IQR=3−1=2 and 1.5×IQR=3, so lower fence=1−3=−2,upper fence=3+3=6.

Step 5, whiskers. The smallest value inside the fences is 0; the largest is 4 (the 7 is outside). So the whiskers run from 0 up to 1, and from 3 up to 4.

Step 6, outliers. Only 7 is beyond a fence: it is drawn as a separate point.

In R, boxplot.stats() returns exactly these pieces: the whisker ends, hinges and median in $stats, and the outliers in $out.

R
sprayC <- InsectSprays$count[InsectSprays$spray == "C"]
quantile(sprayC)
boxplot.stats(sprayC)
ggplot(data.frame(count = sprayC), aes(x = count, y = "")) +
  geom_boxplot(width = 0.4) +
  labs(x = "insects remaining (spray C)", y = NULL)
output
  0%  25%  50%  75% 100% 
 0.0  1.0  1.5  3.0  7.0 
$stats
[1] 0.0 1.0 1.5 3.0 4.0

$n
[1] 12

$conf
[1] 0.5877866 2.4122134

$out
[1] 7
A single horizontal boxplot of the 12 insect counts for spray CA single horizontal boxplot of the 12 insect counts for spray C. The box runs from 1 to 3 with the median line at 1.5. The left whisker reaches 0 and the right whisker reaches 4. One point is drawn separately at 7. 0 2 4 6 insects remaining (spray C)

What a boxplot can hide

A boxplot compresses a whole dataset into five numbers plus outliers. That makes it compact, and it also means very different datasets can have identical boxplots.

Example 2.11: One Boxplot, Three Datasets

The three datasets below were constructed to have the same minimum (0), quartiles (25 and 75), median (50) and maximum (100), with 101 observations each. Draw their boxplots and their histograms. What does each picture show?

The function fit5() below stretches a dataset, piece by piece, so that its five-number summary becomes exactly 0, 25, 50, 75, 100. (You don't need to understand how it works; ppoints() and qnorm() produce evenly spread and bell-shaped sets of values, Chapter 5.)

R
fit5 <- function(x) {      # stretch x so its five-number summary is 0, 25, 50, 75, 100
  approx(quantile(x), c(0, 25, 50, 75, 100), xout = x)$y
}
n <- 101
three <- data.frame(
  set = rep(c("flat", "two peaks", "three clusters"), each = n),
  value = c(fit5(ppoints(n)),
            fit5(c(qnorm(ppoints(50), -2, 0.5), qnorm(ppoints(51), 2, 0.5))),
            fit5(c(qnorm(ppoints(34), 0, 0.3), qnorm(ppoints(33), 5, 0.3),
                   qnorm(ppoints(34), 10, 0.3)))))
aggregate(value ~ set, data = three, FUN = fivenum)
output
             set value.1 value.2 value.3 value.4 value.5
1           flat       0      25      50      75     100
2 three clusters       0      25      50      75     100
3      two peaks       0      25      50      75     100

The five-number summaries are identical. So are the boxplots:

R
ggplot(three, aes(x = value, y = set)) +
  geom_boxplot(width = 0.5) +
  labs(x = "value", y = NULL)
Three identical horizontal boxplots, one for each of three datasets labelled flat, two…Three identical horizontal boxplots, one for each of three datasets labelled flat, two peaks and three clusters. Each box runs from 25 to 75 with a median line at 50 and whiskers reaching 0 and 100. flat three clusters two peaks 0 25 50 75 100 value

But the histograms show three completely different distributions:

R
ggplot(three, aes(x = value)) +
  geom_histogram(binwidth = 5, boundary = 0, colour = "white") +
  facet_wrap(~ set) + scale_x_continuous(breaks = c(0, 50, 100)) +
  labs(x = "value", y = "count")
Three histograms of the same three datasets, side by sideThree histograms of the same three datasets, side by side. Flat: roughly level bars from 0 to 100. Three clusters: three separate groups, near 0 to 30, around 50, and 70 to 100, with empty gaps between them. Two peaks: two humps centred near 25 and 75, with almost nothing at 50. flat three clusters two peaks 0 50 100 0 50 100 0 50 100 0 5 10 15 value count

The "two peaks" dataset has almost no values near its median of 50, and the "three clusters" dataset falls into three separate groups with empty gaps between them, a third of its values packed tightly around the median. A boxplot would never tell you either of these things. A boxplot can't show modality. When you have only one group, a histogram is usually more informative; boxplots come into their own when comparing groups.

Side-by-side boxplots

Where boxplots really shine is in comparing a numerical variable across groups. Placed side by side on a common axis, they let you compare centres (the median lines), spreads (the box lengths), skewness (whether the median sits in the middle of its box, and whether one whisker is much longer) and outliers, for many groups at once.

Example 2.12: Which Insecticide Works? ★ lecture example

In an agricultural experiment published by Geoffrey Beall in 1942, plots of crops were treated with one of six insecticides (labelled A to F), 12 plots each, and the insects remaining on each plot were counted. The data are R's InsectSprays. Compare the sprays with side-by-side boxplots and five-number summaries. Which sprays work best? Do they differ in spread? Are there outliers?

One line of ggplot draws a boxplot for every spray on the same axis. Adding the individual plots as faint dots shows what each box summarizes:

R
ggplot(InsectSprays, aes(x = spray, y = count)) +
  geom_boxplot(outlier.shape = 1, outlier.size = 2.5) +
  geom_jitter(width = 0.12, height = 0, alpha = 0.3) +
  labs(x = "insecticide", y = "insects remaining")
Side-by-side boxplots of insect counts for six sprays, A to F, 12 plots each, with the…Side-by-side boxplots of insect counts for six sprays, A to F, 12 plots each, with the individual counts shown as faint dots. Sprays A, B and F have medians around 14 to 17 insects with wide boxes. Sprays C, D and E have medians between 1.5 and 5 insects with narrow boxes. Spray C has one outlier at 7 and spray D one at 12. 0 10 20 A B C D E F insecticide insects remaining

tapply() applies a function to each group separately:

R
tapply(InsectSprays$count, InsectSprays$spray, median)
tapply(InsectSprays$count, InsectSprays$spray, IQR)
output
   A    B    C    D    E    F 
14.0 16.5  1.5  5.0  3.0 15.0 
    A     B     C     D     E     F 
 6.25  5.00  2.00  1.25  2.25 10.00 

Reading the plot from left to right, and comparing the groups feature by feature:

  • Centre. The sprays fall into two clear groups. A, B and F leave a median of 14 to 16.5 insects per plot; C, D and E leave 1.5 to 5. Spray C is the most effective, with a median of just 1.5 insects.
  • Spread. The effective sprays are also much less variable: their boxes are narrow (IQRs of 1.25 to 2.25 insects, against 5 to 10 for A, B and F). In count data, spread usually grows with the average; Chapter 4 explains why.
  • Outliers. Spray C has one plot with 7 insects (Example 2.10), and D one with 12. Before blaming the spray, a careful scientist would check whether those plots were unusual: a field edge, a missed application, a recording error.
  • Overlap. No plot treated with C, D or E had more insects than the median plot of A, B or F. The difference between the two groups is not a matter of a few lucky plots.

Because the sprays were assigned to plots in a designed experiment, a difference this large can be attributed to the sprays themselves (Chapter 1's randomization argument), not to differences between plots.

Boxplots: strengths and weaknesses

feature boxplots
Used for one numerical variable, and especially comparing it across several groups
Shows well median, middle half, overall extent, outliers; differences in centre and spread between groups
Strengths compact; resistant (built from quantiles); dozens of groups fit on one plot; flags outliers automatically
Weaknesses hides the shape inside the box (can't show peaks: Example 2.11); hides the sample size (a box from 5 values looks as solid as one from 5,000); details depend on the quartile rule

A good habit is to add the raw data as dots on top of a boxplot, as in Example 2.12, whenever there are few enough points to see.

Check Yourself

In birthwt, the mean birth weight is 2,945 g and the standard deviation 729 g. What is the z-score of a baby weighing 2,500 g, the threshold for "low birth weight"? (Two decimals.)

A dataset has Q1=8 and Q3=12. Above what value is an observation flagged as a possible outlier?

In a boxplot, the median line is much closer to Q1 than to Q3, and the upper whisker is much longer than the lower one. What does that suggest?

Think About It: When Is an Outlier Evidence?

In a study of 30 forensic labs, one lab's error rate is far above the upper fence. Give two different explanations for the outlier, one that makes it a problem with the data and one that makes it a genuine signal about the labs. What extra information would help you decide?

A data problem: the lab's errors were counted differently, or a typo turned 1.2% into 12%. A genuine signal: that lab really does make more errors, perhaps because of poor training, faulty equipment or an overwhelming caseload. To decide, you'd check how the figure was recorded, look at the lab's error rate in previous years, and compare its procedures with other labs'. An outlier is a question, not an answer; deleting it without investigation can throw away the most important finding in the data.

Key Takeaways

  • A z-score z=(x−x‾)/s measures position in standard deviations; it doesn't depend on units.
  • Under y=a+bx: the mean becomes a+bx‾, the SD becomes |b|s.
  • The 1.5 × IQR rule flags possible outliers. Investigate them; don't just delete them.
  • A boxplot draws the five-number summary and outliers. Build it by hand: sort, median, quartiles, fences, whiskers, outliers.
  • Identical boxplots can hide very different shapes. Boxplots are at their best side by side, comparing groups.

2.5 Pictures that tell the truth

The right picture for the variable

The type of variable (Section 1.4) decides the picture. Every picture is good at some things and bad at others; this table collects them. (The ggplot2 functions are geom_histogram(), geom_boxplot(), geom_jitter() or geom_dotplot(), geom_bar(), geom_point(), geom_line(), and geom_qq() with geom_qq_line(), in the order of the table.)

picture used for shows well watch out for
histogram one numerical variable shape: peaks, skew, gaps depends on bins; poor for small n
boxplot one numerical variable, across groups centre, spread, outliers; comparing groups hides shape and sample size
dot plot / strip plot small datasets every single value cluttered for large n
bar chart one categorical variable counts or percentages per category must start at zero
scatterplot two numerical variables direction, form, strength, unusual points overplotting for large n; association isn't causation
line graph a variable over time trends, cycles, sudden changes joins points that may not be connected
Gaussian Q-Q plot is it bell-shaped? departures from a Gaussian shape, especially in the tails takes practice to read

Bar charts

A bar chart shows a categorical variable: one bar per category, with height equal to the count (or percentage). Unlike a histogram, the bars are separated by gaps, because the categories are separate, and for a nominal variable their order is up to you: sorting the bars by height usually makes the chart easier to read.

Example 2.13: What Kinds of Glass?

Draw a bar chart of the six glass types in fgl. What is the mode?

table() gives the counts; geom_bar() counts and draws them in one step. reorder() sorts the bars from most to least common.

R
table(fgl$type)
ggplot(fgl, aes(x = reorder(type, type, function(t) -length(t)))) +
  geom_bar(width = 0.7) +
  labs(x = "glass type", y = "number of fragments")
output

 WinF WinNF   Veh   Con  Tabl  Head 
   70    76    17    13     9    29 
Bar chart of the number of glass fragments of each type in the fgl data, sorted from most…Bar chart of the number of glass fragments of each type in the fgl data, sorted from most to least common: WinNF 76, WinF 70, Head 29, Veh 17, Con 13, Tabl 9. 0 20 40 60 WinNF WinF Head Veh Con Tabl glass type number of fragments

The modal category is WinNF (building window, non-float), with 76 fragments, just ahead of WinF with 70. Together, building windows make up 146/214≈68% of the fragments. Any classifier for this dataset (Example 1.3) must do better than the lazy rule "always guess WinNF", which would be right 76/214≈36% of the time.

Why sort the bars? For a nominal variable the order is arbitrary, so choose the order that helps the reader: sorted by height, the chart can be read like a ranking. For an ordinal variable (such as "mild, moderate, severe"), keep the natural order instead.

Bar charts: easy to read and compare; but bars must start at zero (Section "Honest and dishonest graphs" below), and pie charts showing the same information are much harder to judge by eye.

Scatterplots

A scatterplot shows the relationship between two numerical variables measured on the same individuals (units): one point per unit, with one variable on each axis.

Example 2.14: Hot Days and Ozone

Ground-level ozone forms when sunlight drives chemical reactions between pollutants. Draw a scatterplot of ozone against temperature for New York in summer 1973, and describe the relationship.

R
ggplot(airquality, aes(x = Temp, y = Ozone)) +
  geom_point(alpha = 0.7, na.rm = TRUE) +
  labs(x = "maximum temperature (°F)", y = "ozone (ppb)")
Scatterplot of daily ozone in parts per billion against maximum temperature in degrees…Scatterplot of daily ozone in parts per billion against maximum temperature in degrees Fahrenheit for 116 days. Ozone is low, under about 40, on days below 75 degrees, and rises steeply and more variably on hotter days, reaching 100 to 170 on some days above 80 degrees. 0 50 100 150 60 70 80 90 maximum temperature (°F) ozone (ppb)

A description of a scatterplot should cover four things.

  • Direction. Hotter days have more ozone: a positive association (as one variable goes up, the other tends to go up).
  • Form. The relationship isn't a straight line: ozone stays low until about 75°F, then climbs steeply. It curves.
  • Strength. Fairly strong: temperature tells you a lot about ozone, though not everything.
  • Unusual features. The spread grows with temperature: days of 80°F or more range from under 10 to almost 170 ppb.

Is temperature causing the ozone? Partly (heat and sunlight drive the chemistry), but sunny, hot, still days also trap pollution, so temperature, sunlight and wind all move together. Chapter 6 measures association with correlation; Chapter 1's DAGs are how we'd think about cause.

Example 2.15: Four Datasets, One Summary ★ lecture example

In 1973 the statistician Francis Anscombe constructed four small datasets, each with 11 pairs (x,y). They're in R as anscombe. Compute the mean and standard deviation of each x and y, and the correlation (Chapter 6) between them. Then plot them.

sapply() applies a function to every column of a data frame:

R
sapply(anscombe, mean)
sapply(anscombe, sd)
sapply(1:4, function(i) cor(anscombe[[i]], anscombe[[i + 4]]))
output
      x1       x2       x3       x4       y1       y2       y3 
9.000000 9.000000 9.000000 9.000000 7.500909 7.500909 7.500000 
      y4 
7.500909 
      x1       x2       x3       x4       y1       y2       y3 
3.316625 3.316625 3.316625 3.316625 2.031568 2.031657 2.030424 
      y4 
2.030579 
[1] 0.8164205 0.8162365 0.8162867 0.8165214

Every x has mean 9 and standard deviation 3.32; every y has mean 7.50 and standard deviation 2.03; every correlation is 0.82. By the numbers, the four datasets are identical. Now look:

R
long <- data.frame(set = rep(paste("dataset", 1:4), each = 11),
                   x = unlist(anscombe[1:4]), y = unlist(anscombe[5:8]))
ggplot(long, aes(x, y)) +
  geom_point(size = 2.5) +
  facet_wrap(~ set)
Four scatterplots in a 2 by 2 gridFour scatterplots in a 2 by 2 grid. Dataset 1 shows a noisy straight-line relationship. Dataset 2 shows a smooth curve that rises and then falls. Dataset 3 shows a perfect straight line except for one point far above it. Dataset 4 shows ten points stacked at x equals 8 and one point far to the right at x equals 19. dataset 3 dataset 4 dataset 1 dataset 2 5 10 15 5 10 15 5.0 7.5 10.0 12.5 5.0 7.5 10.0 12.5 x y

They couldn't be more different: a noisy line, a curve, a perfect line spoiled by one outlier, and a single extreme point creating the whole "relationship". Summary statistics are compressions, and compressions lose information. This is the two-variable version of Example 2.11's identical boxplots. Always plot your data.

What each picture says. Dataset 1 is what the summary numbers suggest. In dataset 2 the true relationship is a curve, so a straight-line summary is the wrong model. In dataset 3 a single unusual point changes the slope and correlation. In dataset 4 there is no relationship at all among ten of the points; one point at x=19 creates the whole correlation. A prediction for a new x would go badly wrong in datasets 2 and 4 if we trusted the summary numbers alone.

Is it bell-shaped? The Gaussian Q-Q plot

Many methods later in the course assume data come from a bell-shaped (Gaussian) distribution. A histogram is a poor judge of this, especially for small samples, because its appearance depends so much on the bins. A better tool is the Gaussian quantile–quantile (Q-Q) plot. (Most books and software call the bell curve the normal distribution, and this plot a normal Q-Q plot; R's function is qqnorm(). These notes use the name Gaussian, for reasons explained in Section 5.3.)

The idea is simple. Sort the data. Then ask: if the data really came from a bell-shaped distribution, where would the smallest value be expected to sit? The second smallest? The median? A Q-Q plot puts these expected positions (from the Gaussian distribution, Chapter 5) on the horizontal axis and the actual sorted data on the vertical axis. If the data are bell-shaped, actual and expected agree up to a change of units, and the points lie close to a straight line. Curves and bends show how they depart:

Reading a Gaussian Q-Q plot

Choose where the data come from and how many observations to draw. The left panel shows the histogram with the best-fitting bell curve. The right panel is the Gaussian Q-Q plot. Try each shape several times with new sample: learn what a straight line looks like when the data really are Gaussian, and how each kind of departure bends it.

LeftLeft: histogram of a random sample with a Gaussian curve. Right: the Gaussian Q-Q plot of the same sample with a reference line.

Example 2.16: Are Birth Weights Gaussian?

Draw Gaussian Q-Q plots of the birth weights in birthwt and of the ozone readings in airquality. Which looks bell-shaped?

R
both <- rbind(data.frame(var = "birth weight (g)", value = birthwt$bwt),
              data.frame(var = "ozone (ppb)", value = na.omit(airquality$Ozone)))
ggplot(both, aes(sample = value)) +
  geom_qq() + geom_qq_line() +
  facet_wrap(~ var, scales = "free_y") +
  labs(x = "Gaussian quantiles", y = "data")
Two Gaussian Q-Q plots side by sideTwo Gaussian Q-Q plots side by side. Left, birth weights: the points lie close to the straight reference line along its whole length, with slight wobbles at the ends. Right, ozone: the points curve upwards, lying above the line at both ends, the signature of right skew. birth weight (g) ozone (ppb) -3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 -50 0 50 100 150 1000 2000 3000 4000 5000 Gaussian quantiles data

Birth weights hug the line: approximately Gaussian. Ozone bends upwards, sitting above the line at both ends: its smallest values are not as small as a bell would predict (ozone can't go below 0), and its largest are much larger. That's the signature of right skew, as the histogram showed. For skewed data, a common remedy is to analyse the logarithm of the values instead (try a Q-Q plot of log(airquality$Ozone)).

Why it matters. Later chapters use methods that assume a Gaussian shape. For birth weights those methods can be used with confidence; for raw ozone readings they would understate how often very high days occur, which is exactly what a public-health warning system needs to predict.

Honest and dishonest graphs

A graph is an argument, and it can mislead as easily as words. The most common trick is with the axis.

How to make a difference look bigger

The bars show the average birth weight of babies born to mothers who did and didn't smoke (Baystate Medical Center, 1986: 3,056 g and 2,772 g). Move the start of the vertical axis up from zero. The numbers never change, but the picture does. The lie factor compares the size of the effect shown in the graphic with the size of the effect in the data; an honest bar chart has a lie factor of 1.

Two bars showing average birth weight for non-smokers and smokers, with an adjustable…Two bars showing average birth weight for non-smokers and smokers, with an adjustable starting value for the vertical axis.

Watch Out: Checklist for an Honest Graph

  • Bars start at zero. Bar length is read as size.
  • Label the axes, with units.
  • Don't hide the variation. A bar of averages hides the individual observations; show them, or at least their spread.
  • Compare like with like. Totals from groups of different sizes should usually be rates (per 100,000 people, per day).
  • Don't let decoration distort. 3-D bars and pie charts make sizes hard to judge accurately.

Think About It: Who Made This Graph, and Why?

A company's annual report shows a bar chart of profits over five years with the vertical axis starting at $9.5 million; profits rose from $9.6 to $10.1 million. Who benefits from this choice of axis? Now imagine a news article about rising crime using a line graph whose axis starts at zero, making a 40% rise look gentle. Is starting a line graph at zero always the honest choice?

The company's bars exaggerate a 5% rise into what looks like a six-fold one (bars of height 0.1 and 0.6 above the axis), which flatters management. Line graphs are different: their message is the change over time, read from the slope, not the length of anything, so an axis that doesn't start at zero can be honest, and starting at zero can hide a real and important change. The honest choice depends on what the picture is meant to compare. A good test: would the people who made the graph be happy for you to see the same data plotted another reasonable way?

History: The Inventors of Statistical Graphics

The Scottish engineer and economist William Playfair invented the line graph and the bar chart in his Commercial and Political Atlas of 1786, to make England's trade figures visible at a glance, and the pie chart in 1801.

In 1858, two years after returning from the Crimean War, Florence Nightingale used "rose" diagrams (polar area charts) to show that far more British soldiers had died of preventable diseases in army hospitals than of wounds. Her graphics helped persuade the government to reform military sanitation, and she became the first woman elected a Fellow of the Royal Statistical Society.

A century later the American statistician John Tukey urged statisticians to explore data visually before testing anything, and invented the boxplot along the way; his book Exploratory Data Analysis (1977) gave the approach its name.

Check Yourself

In Anscombe's quartet, all four datasets have the same means, standard deviations and correlation. What is the lesson?

Key Takeaways

  • Match the picture to the variable types: histogram or boxplot (numerical), bar chart (categorical), scatterplot (two numerical), line graph (over time).
  • Describe a scatterplot by direction, form, strength and unusual points.
  • A Gaussian Q-Q plot checks for bell shape: straight means Gaussian; ends curving away mean skew or heavy tails.
  • Bar charts start at zero. Always plot the data: summaries can hide anything (Anscombe).

2.6 Two categorical variables and Simpson's paradox

Contingency tables

When both variables are categorical, we summarize them with a contingency table (a two-way table of counts): one row for each category of one variable, one column for each category of the other, and in each cell the number of units with that combination. Chapter 3 uses one for the Titanic. To compare groups, convert the counts to row or column percentages, so that groups of different sizes can be compared fairly.

Example 2.17: Berkeley Admissions ★ lecture example

In fall 1973, the University of California, Berkeley received about 12,800 applications to its graduate programmes. Men were admitted at noticeably higher rates than women, and the university was concerned it might face a lawsuit for sex discrimination. R's UCBAdmissions contains the applications to the six largest departments. Compute the admission rates for men and women overall, and then department by department.

UCBAdmissions is a three-way table: admitted or rejected, by sex, by department. margin.table() adds up over the dimensions you leave out, and prop.table(..., 2) turns counts into column percentages.

R
overall <- margin.table(UCBAdmissions, c(1, 2))       # pool the departments
overall
round(prop.table(overall, 2), 3)                      # admission rate by sex
by_dept <- prop.table(UCBAdmissions, c(2, 3))["Admitted", , ]   # rate by sex and department
round(by_dept, 3)
margin.table(UCBAdmissions, c(2, 3))                  # number of applicants
output
          Gender
Admit      Male Female
  Admitted 1198    557
  Rejected 1493   1278
          Gender
Admit       Male Female
  Admitted 0.445  0.304
  Rejected 0.555  0.696
        Dept
Gender       A     B     C     D     E     F
  Male   0.621 0.630 0.369 0.331 0.277 0.059
  Female 0.824 0.680 0.341 0.349 0.239 0.070
        Dept
Gender     A   B   C   D   E   F
  Male   825 560 325 417 191 373
  Female 108  25 593 375 393 341

Pooled over the six departments, men were admitted at a rate of 11982691≈44.5%,women at5571835≈30.4%. Yet department by department, women did about as well as men, and better in four of the six departments (dramatically so in department A: 82% against 62%).

How can women do as well or better in each department but worse overall? Look at where they applied (the last table). Most men applied to departments A and B, which admitted most applicants. Most women applied to departments C to F, which were far more competitive and rejected most applicants of either sex. Pooling the departments mixes up "which sex" with "which department". The widget below lets you see this happen.

A plot of the department-by-department rates makes the pattern visible at a glance:

R
rates <- as.data.frame(as.table(by_dept))
names(rates) <- c("sex", "dept", "rate")
ggplot(rates, aes(x = dept, y = rate, shape = sex)) +
  geom_point(size = 3.5) +
  geom_hline(yintercept = c(0.445, 0.304), linetype = "dashed") +
  labs(x = "department", y = "admission rate", shape = NULL)
Dot plot of graduate admission rates at Berkeley in 1973 for six departments, A to F…Dot plot of graduate admission rates at Berkeley in 1973 for six departments, A to F, with one point for men and one for women in each. Rates fall from about 0.6 to 0.8 in departments A and B to under 0.1 in department F. Women's points are higher than men's in A, B, D and F, and slightly lower in C and E. Dashed horizontal lines mark the pooled rates: 0.45 for men and 0.30 for women. 0.2 0.4 0.6 0.8 A B C D E F department admission rate Male Female

Within departments the two sexes' points are close together, and women's are often higher; the big gap between the dashed (pooled) lines comes entirely from which departments each sex applied to. Inference about the mechanism ("is there bias in admissions decisions?") needs the within-department comparison, not the pooled one.

Berkeley 1973: a paradox in six departments

Graduate admissions at UC Berkeley in fall 1973, for the six largest departments (R's UCBAdmissions). Each circle is one department, for men (blue) or women (orange); its height is the admission rate and its area is the number of applicants. The dashed lines are the overall rates when the departments are pooled. Tick departments on and off and watch the pooled rates move. Then compare men and women within each department.

Admission rate by department for men and women, with circle area proportional to the…Admission rate by department for men and women, with circle area proportional to the number of applicants, and dashed lines showing the pooled admission rates for the selected departments.

Definition: Simpson's Paradox

Simpson's paradox occurs when an association between two variables within each of several groups reverses (or disappears) when the groups are combined. It happens when a third variable is related both to the grouping and to the outcome, so that the groups being compared are spread very differently across its levels.

Causal Inference: Which Table Should You Believe?

Simpson's paradox isn't a paradox of arithmetic: both tables are correct. It's a question of which comparison answers your question, and that depends on the causal structure. Draw the diagram:

A causal diagram for the Berkeley admissions dataA causal diagram for the Berkeley admissions data. Sex has an arrow to department applied to, and department has an arrow to admission. A dashed arrow from sex directly to admission represents possible discrimination within departments.sexdepartment applied toadmittedcompetitivenessdiscrimination within a department?
Department choice lies on a route from sex to admission.

Sex influences which department a person applies to, and the department strongly influences admission. If the question is "do departments treat men and women differently?", we compare within departments, holding department fixed, and find no evidence against women. If the question were "how does being a woman affect your overall chance of admission, all things included?", the pooled numbers describe that total effect, which runs through department choice. The data can't tell us which question to ask. The diagram can.

The same pattern turns up everywhere: a hospital with worse survival rates overall that is better for every type of patient (because it takes the sickest patients), or a treatment that looks harmful overall but helps in every subgroup. Before pooling data across groups, ask whether the groups differ in ways that also affect the outcome.

Source: P. J. Bickel, E. A. Hammel and J. W. O'Connell (1975), "Sex bias in graduate admissions: data from Berkeley", Science 187, 398–404.

Interlude (Optional): How Spread Out Is a Categorical Variable?

Standard deviations need numbers. How can we measure the spread, or unpredictability, of a categorical variable like glass type? If almost every fragment were window glass, guessing a fragment's type would be easy; if all six types were equally common, it would be hard.

In 1948 Claude Shannon defined the entropy of a categorical distribution with proportions p1,…,pk: H=−∑j=1kpjlog2pjbits. It is 0 when one category has everything (no uncertainty), and as large as possible, log2k, when all k categories are equally common. You can think of it as the average number of yes/no questions needed to identify a randomly chosen category, if you ask cleverly. For a fair coin, H=−(12log212+12log212)=1 bit: one yes/no question.

R
p <- table(MASS::fgl$type) / nrow(MASS::fgl)   # proportions of the six glass types
-sum(p * log2(p))                               # entropy, in bits
log2(6)                                         # the maximum for six types
output
[1] 2.176534
[1] 2.584963

The six glass types have entropy 2.18 bits, below the maximum of 2.58 because window glass is much more common than the rest. Entropy is the foundation of information theory, data compression, and the way decision-tree algorithms in machine learning choose which question to ask first. It is also behind the cross-entropy loss used to train classifiers (Section 2.2). Chapter 4 returns to it.

Why it matters: spread isn't only about numbers; unpredictability can be measured for any variable.

Check Yourself

Hospital A treated 1,000 patients and 90% survived. Hospital B treated 1,000 patients and 80% survived. But hospital B takes most of the region's severe trauma cases.

Can you conclude hospital A gives better care?

Think About It: Pooling in Your Own Life

A college reports that its average class size fell from 30 to 26 over five years. But most students say their classes feel bigger than ever. Could both be true? Think about who is being averaged.

Yes. The college averages over classes; students experience the average over students. Suppose there are many small seminars and a few huge lectures: most classes are small, but most students sit in the big ones, because that's where the students are. If the college added many small seminars while the big lectures grew, the average class size would fall while the typical student's class grew. It's the same trap as the average of the states in Example 1.8, and a cousin of Simpson's paradox: always ask what the units of an average are.

Key Takeaways

  • A contingency table summarizes two categorical variables; compare groups using row or column percentages.
  • Simpson's paradox: a comparison can reverse when groups are pooled, because a third variable is tied to both.
  • Which comparison is right depends on the causal question. Draw the DAG before pooling.

Prediction and inference in this chapter

Looking back, every tool in this chapter serves the course's two goals.

What we can't yet do is say how sure we should be: whether the difference between two boxplots could be a fluke of these particular samples. That needs probability, which is the subject of the next three chapters.

2.7 Exercises

Each exercise has a hint and an answer. Do the work by hand where the exercise says so, and use R to check.

Exercises

  1. Waiting for Old Faithful. Draw a histogram of faithful$waiting (minutes until the next eruption). Describe its shape, centre and spread. Then draw a scatterplot of waiting against eruptions, and explain how a ranger could use it to predict the next eruption.

    Use ggplot(faithful, aes(x = waiting)) + geom_histogram(binwidth = 5). Look for the same feature as in Example 2.1. For the scatterplot, put eruptions on the horizontal axis, since it is known first.

    Bimodal, with peaks near 55 and 80 minutes; median 76, mean 70.9, SD 13.6, IQR 24 minutes (the two clusters make the spread large). The scatterplot shows two clusters on a rising line: short eruptions (about 2 min) are followed by short waits (about 55 min), and long eruptions (about 4.5 min) by long waits (about 80 min). A ranger can predict the next wait from the length of the last eruption.

  2. Mean, median and skew. For the islands dataset (areas of the world's major landmasses, in thousands of square miles), compute the mean and median. Explain the difference. Then repeat for log(islands).

    mean(islands), median(islands). Draw hist(islands): what does the shape look like? Taking logs pulls in a long right tail.

    Mean 1,253, median 41 (thousand square miles). The distribution is extremely right-skewed: a few continents (Asia, Africa, North America, ...) are enormous, while most of the 48 landmasses are small islands. After taking logs, the mean is 4.45 and the median 3.71, much closer together, because the log transformation reduces the right skew.

  3. By hand. Six fingerprint examiners took 14, 9, 11, 22, 12 and 10 minutes to complete the same comparison. Compute the mean, median, sample standard deviation, quartiles (R's rule) and IQR by hand. Which examiner is a possible outlier by the 1.5 × IQR rule? Check every answer in R.

    Sort first: 9, 10, 11, 12, 14, 22. For the quartiles, the positions are 1+5×0.25=2.25 and 1+5×0.75=4.75. For the SD, follow the six-step algorithm in Section 2.3; the deviations from the mean are −4,−3,−2,−1,1,9.

    Mean 13; median 11.5; squared deviations 16, 9, 4, 1, 1, 81 sum to 112, so s2=112/5=22.4 and s≈4.73 minutes. Q1=10+0.25×1=10.25, Q3=12+0.75×2=13.5, IQR =3.25. Upper fence =13.5+1.5×3.25=18.375, so the examiner who took 22 minutes is a possible outlier.

  4. Changing units. In Exercise 3, convert the times to seconds. Without recomputing from the data, give the new mean and standard deviation, and explain using the theorem on changing units.

    Seconds =60× minutes, so a=0 and b=60 in y=a+bx.

    Mean =60×13=780 seconds; SD =60×4.73≈284 seconds. Multiplying every value by b multiplies both the mean and the SD by b (here b>0).

  5. Chebyshev versus the rule of thumb. For Old Faithful's eruption lengths, faithful$eruptions, compute the fraction of eruptions within 1 standard deviation of the mean, and within 2. Compare with the 68–95 rule of thumb and with Chebyshev's guarantee. Explain any difference using the shape of the data.

    With e <- faithful$eruptions, the fraction within one SD is mean(abs(e - mean(e)) <= sd(e)). Change the 1 to a 2 for two SDs.

    55.1% within 1 SD (the rule of thumb says about 68%) and 100% within 2 SDs (rule: 95%; Chebyshev guarantees more than 75%). The rule of thumb is for single-peaked, bell-shaped data; Old Faithful is bimodal, with few eruptions near the mean, so fewer than usual lie within 1 SD. Chebyshev still holds, as it must for any data.

  6. Glass. Using fgl, draw side-by-side boxplots of refractive index (RI) by glass type. Which types have the largest spread? Which have outliers? Would refractive index alone be a good way to tell window glass from headlamp glass? (Compare with barium in Example 1.3.)

    ggplot(fgl, aes(x = type, y = RI)) + geom_boxplot(). Compare the boxes for WinF, WinNF and Head: how much do they overlap?

    WinNF, Con and Tabl have the largest SDs (about 3.1 to 3.8); WinNF has the most outliers (12), and every type except Con has at least two. The boxes for window glass and headlamp glass overlap heavily (medians about −0.2 to −0.9 for windows and −1.5 for headlamps), so refractive index alone separates them poorly, much worse than barium.

  7. Michelson revisited. Using morley, compute the mean and standard deviation of each experiment separately with tapply(). Does the overall standard deviation (79 km/s) overstate the run-to-run scatter within an experiment? Why?

    tapply(morley$Speed, morley$Expt, sd). The overall SD mixes two kinds of variation: within each experiment, and between the experiments' averages.

    Experiment means (coded): 909, 856, 845, 820.5, 831.5; SDs 104.9, 61.2, 79.1, 60.0, 54.2. Three of the five within-experiment SDs are well below the overall 79.0. The overall SD also includes the differences between the experiment averages (from 820 to 909), so it overstates the scatter you'd see within a single experiment (experiment 1 is unusually variable, and experiment 3 about matches the overall SD).

  8. A misleading graph. Find a graph in the news or on social media that you think misleads. Describe what's wrong with it using the checklist in Section 2.5, and sketch an honest version.

    Check the axes first (where do they start? are they labelled?), then ask whether totals should be rates, and whether decoration distorts sizes.

    Answers will vary. A good answer names the specific checklist item that's violated, explains how it changes the reader's impression (for example, by computing a lie factor as in the widget), and sketches a version that fixes it.

  9. Simpson's paradox in R. Using UCBAdmissions, compute the admission rate for women and for men pooled over departments C, D, E and F only. Then compute it for each of those departments. Is there a reversal? Explain using the widget.

    u <- UCBAdmissions[, , c("C", "D", "E", "F")], then use margin.table() and prop.table() as in Example 2.17. Think about whether these four departments differ much in how selective they are.

    Pooled over C–F: men 25.5%, women 26.5%. By department: C men 36.9%, women 34.1%; D 33.1% vs 34.9%; E 27.7% vs 23.9%; F 5.9% vs 7.0%. No reversal: women do slightly better in two departments and slightly worse in two, and slightly better pooled. Simpson's paradox needs groups that differ a lot in the outcome and in who applies to them; once departments A and B (which admitted most applicants, and received mostly men's applications) are left out, the effect disappears. Tick only C–F in the widget to see this.

  10. Insecticides. For InsectSprays, compute the mean and standard deviation of the counts for each spray. Plot the standard deviation against the mean for the six sprays. What pattern do you see? Why might count data behave this way?

    m <- tapply(InsectSprays$count, InsectSprays$spray, mean) and similarly s with sd. Then plot(m, s). Think about what can happen to a count that averages 2 compared with one that averages 15.

    Means: A 14.5, B 15.3, C 2.1, D 4.9, E 3.5, F 16.7; SDs: 4.7, 4.3, 2.0, 2.5, 1.7, 6.2. The SD increases with the mean. A count that averages 2 can't vary much, because it can't go below 0; a count that averages 15 has room to vary a lot in both directions. Chapter 4's Poisson distribution, where the variance equals the mean, makes this precise.