Chapter 2
Describing data
Lectures 3–4 · centre, spread, shape, and pictures that tell the truth
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:
- 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);
- the R code that computes it, so that you can use it on real datasets with hundreds of values;
- 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.)
summary(faithful$eruptions) # minutes
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:
ggplot(faithful, aes(x = eruptions)) +
geom_histogram(binwidth = 0.2, boundary = 1.6) +
labs(x = "eruption length (minutes)", y = "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 .
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 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
- Find the range. Identify the smallest and largest observations.
- 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.
- 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 contains values with . Say which rule you used.
- Tally. Go through the data once, making a tally mark in the bin of each observation. Check that the counts add up to .
- 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.
- 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 , , , and . These cover 650 to 1070. Using the left-endpoint rule, the value 900 belongs to and the three values of 1000 belong to .
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. |
|---|---|---|---|
| 650 | 1 | 0.05 | |
| 740, 760 | 2 | 0.10 | |
| 810, 850, 850, 880 | 4 | 0.20 | |
| 900, 930, 930, 950, 960, 960, 980, 980, 980 | 9 | 0.45 | |
| 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, , matching our rule:
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
[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
The counts 1, 2, 4, 9, 4 match our table.
Shape. The distribution has a single peak in , 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, . 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.
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:
- shape: how many peaks, whether it is symmetric or skewed, and whether there are gaps or unusual values;
- centre: where a typical value lies;
- spread: how much the values vary.
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.
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
Which side has the long tail: the side near 0, or the side with the occasional very high days?
Bounded below by zero with a long tail of occasional high-ozone days: right-skewed. (You can check with hist(airquality$Ozone).)
Too-narrow bins give many small spiky peaks, not two clear ones. What kind of mixture would produce two genuine peaks?
Skewness is about a long tail, not about two peaks. What could make two separate "typical" heights?
Two peaks usually mean two groups mixed together, like Old Faithful's short and long eruptions. When you see bimodality, look for the hidden grouping variable.
In a density histogram, a bin from 20 to 30 contains 5 of 200 observations. What is the height of its bar?
First find the relative frequency (5 out of 200), then divide by the bin width.
Relative frequency ; density
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 . The subscript in just labels the observations in the order they were recorded. When we sort them from smallest to largest, we write
Definition: Sample Mean
The sample mean is the ordinary average: In R: mean(x).
Definition: Sample Median
The sample median is the middle value of the sorted data.
- If is odd, it is the observation in position : .
- If is even, there are two middle observations, in positions and , and the median is their average:
.
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, .
Mean. The values add to
Median. Sort: 9.8, 10.4, 11.0, 12.1, 15.3. With (odd), the median is in position , so 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, .
Mean. The sum is
Median. Sort: 7, 10, 10, 12, 13, 14, 14, 14, 17, 20, 20, 23. With (even), the two middle values are in positions and . Both are 14, so
In 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)
[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:
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)
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.
oz <- airquality$Ozone
sum(!is.na(oz)) # number of days with a reading
mean(oz, na.rm = TRUE)
median(oz, na.rm = TRUE)
[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:
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")
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:
table(sprayA) # how often each count occurs
names(which.max(table(sprayA))) # the most frequent value
table(MASS::fgl$type)
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 , is computed in three steps.
- Sort the data.
- Let (that is, rounded down to a whole number). Delete the smallest and the largest observations.
- Average the observations that remain.
In R: mean(x, trim = alpha). A "10% trimmed mean" has .
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
Median. Sorted: 0.079, 0.080, 0.081, 0.083, 0.82. The middle (third) value is 0.081.
20% trimmed mean. Here
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
[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:
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)")
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.
- Trim 0%: nothing is removed, and the trimmed mean is the ordinary mean.
- Trim a little: the most extreme values go, and the result moves away from the mean.
- Trim almost 50% from each end: only the middle one or two values remain, and their average is the median. (R treats
trim = 0.5as the median.)
So choosing a trimming fraction is choosing how much to trust the extremes. The widget below makes the journey visible on the ozone data.
Choosing a measure of centre
| measure | what it is | strengths | weaknesses |
|---|---|---|---|
| mean | balance point | uses every value; easy algebra; links to totals (total = 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 , and every data value charges you a penalty depending on how far it is from . Which makes the total penalty smallest? The answer depends on the penalty rule. Try it before reading the theorem.
Theorem: Mean, Median and Mode as Best Guesses
For observations :
- The total squared distance is smallest when , the mean.
- The total absolute distance is smallest when is a median.
- The number of misses, , is smallest when is a mode.
- The deviations from the mean always add to zero:
.
Part 4 (needed for part 1). Split the sum and use :
Part 1. Let
A proof without calculus. Write
Part 2. Imagine sliding to the right by a tiny amount , not passing any data point. Every observation to the right of gets closer, and every observation at or to the left of gets further away. Write for the number of observations at or to the left of , and for the number to the right. Then the total absolute distance changes by If more observations lie to the right of (), this is negative and moving right helps; if more lie to the left, moving left helps. As 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 : the middle value when is odd, and any point between the two middle values (including their average) when is even. These are the medians.
Part 3. If is not one of the data values, every observation is a miss. If equals a value that occurs times, the number of misses is . This is smallest when is as large as possible, that is, when 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 is a rule that says how bad it is to guess when the truth turns out to be . 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 | big misses, very heavily | the mean | |
| absolute error | every unit of error equally | the median | |
| zero–one | if , else | 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.
Sort them first. With 6 values (an even number), average the values in positions 3 and 4.
Sorted: 9, 10, 11, 12, 14, 22, so the median is
Which summary do a few huge values pull towards them?
They are equal for symmetric data. Is this distribution symmetric?
The few mansions pull the mean up; the median stays near a typical house. That's why news reports quote the median house price.
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.
Remove 7 and 23. The remaining 10 values sum to
The mean is best when the penalty is the square of the error. Here every call of error costs the same $1. Which part of the theorem covers that?
The mode is best when only an exact hit counts. Here being off by 1 costs less than being off by 10.
Equal cost per unit of error is absolute loss, which the median minimizes.
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 = balance point; median = middle of the sorted data (average the two middle values when 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: .
For the toxin concentrations of Example 2.3, the range is 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, , 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 is The sample standard deviation is its square root, . It is measured in the same units as the data. In R: var(x) and sd(x).
Idea: Algorithm: Standard Deviation by Hand
- Compute the mean .
- For each observation, compute the deviation . (Check: they add to 0.)
- Square each deviation.
- Add up the squares.
- Divide by . This is the variance .
- Take the square root. This is the standard deviation .
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, .
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.
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)
[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:
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)")
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.
Why divide by rather than ? The deviations are measured from , which was computed from the same data and therefore sits right in the middle of them. Theorem part 1 says is the point that makes the sum of squared deviations as small as possible, so measuring from gives a slightly smaller sum than measuring from the true population mean would. Dividing by instead of inflates the answer just enough to correct for this on average. Chapter 8 makes this precise: is an unbiased estimator of the population variance. For large 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 and ), and about 95% within two (between and ). (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.
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")
within_1_sd within_2_sd
0.6772487 0.9629630
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 , the fraction of observations more than standard deviations from the mean is less than . 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 of the observations satisfy . Each of them contributes more than to the sum of squared deviations, and the other terms are non-negative, so
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 , the -quantile (or th percentile) of a dataset is a value with roughly a fraction of the observations below it and above it. The first quartile is the 0.25-quantile, the median is the 0.5-quantile, and the third quartile 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:
- Sort the data:
. - Compute the position
. - If is a whole number, the quantile is . Otherwise, write with a whole number and , and move a fraction of the way from to :
In R: quantile(x, p). With this rule always gives the median.
The rule spreads the sorted values evenly from "0% of the way along" (the minimum, position 1) to "100% of the way along" (the maximum, position ). The 25% point is then a quarter of the way along, at position , and if that falls between two observations we interpolate.
Definition: IQR and MAD
- The interquartile range is
: 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, . 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 , , and so on up to .
First quartile. The position is
Median.
Third quartile.
IQR.
MAD. The distances from the median 14 are
| xᵢ | 7 | 10 | 10 | 12 | 13 | 14 |
|---|---|---|---|---|---|---|
| 7 | 4 | 4 | 2 | 1 | 0 | |
| 14 | 14 | 17 | 20 | 20 | 23 | |
| 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
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
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 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).
- Compute the mean, median, standard deviation and IQR of Michelson's measurements.
- How far is his average from the true value, compared with the spread of his measurements?
- Compare the five experiments with boxplots (Section 2.4 explains how to read them). What do you notice?
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)?
[1] 299852.4
[1] 299850
[1] 79.01055
[1] 85
[1] 117.9
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.)
The average is 118 km/s too high, about one and a half standard deviations: 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).
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)")
- 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 | 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 |
| 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
Lab A is right on average. But how far is a typical single reading from Lab A off?
Lab B's readings agree closely with each other. But do they agree with the truth?
Lab A is accurate (unbiased) but not precise; Lab B is precise but biased by 0.30. Lab B's problem can be fixed by recalibration; Lab A's only by averaging many readings or a better instrument. Michelson's measurements had a bit of both.
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.)
Chebyshev: the fraction outside standard deviations is less than .
Using R's rule, find for the six times 9, 10, 11, 12, 14, 22.
The position is
quantile(c(9, 10, 11, 12, 14, 22), 0.25).
The standard deviation uses squared distances from the mean. What does one gigantic value do to that?
The variance is the standard deviation squared, so it's affected even more.
The IQR only depends on the middle half of the data, so one wild value barely moves it.
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()andvar()), 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 averages squared deviations (dividing by ); the standard deviation 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 within SDs, for any data.
- Quantiles by R's rule: position
, 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 is its distance from the mean in units of standard deviations: A z-score of 2 means "two standard deviations above the mean"; 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 () further above average than one who scored 620 on an exam with mean 500 and SD 100 ()? Yes. And z-scores don't depend on the units: converting grams to pounds changes , and by the same factor, which cancels. Here is the general fact.
Theorem: Changing Units
If every observation is transformed to (for constants and ), then In words: adding a constant shifts the centre but not the spread; multiplying by multiplies both by (the spread by , since spread can't be negative).
The mean. Using the sum rules from Section 0.4,
The standard deviation. Each deviation becomes
For example, converting Celsius to Fahrenheit () 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 with and , so its mean is
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?
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
mean sd n
0.7182857 2.2680969 70.0000000
[1] 2.328699
[1] 0.01428571
The z-score is 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:
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")
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 below or above . The values
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, , median, , maximum).
A boxplot draws a box from to 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.
Idea: Algorithm: A Boxplot by Hand
- Sort the data.
- Median. Find the middle value; draw a line there.
- Quartiles. Find and ; draw a box from to , so that the box contains the middle half of the data.
- Fences. Compute
, then the fences and . (Don't draw them; they are for checking.) - Whiskers. Draw a line from the box down to the smallest observation inside the fences, and up to the largest observation inside the fences.
- Outliers. Plot every observation beyond a fence as a separate point.
- Label the axis with the variable and its units.
Work through the algorithm in the widget, one step at a time.
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. , so average the 6th and 7th values:
Step 3, quartiles. For ,
Step 4, fences.
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.
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)
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
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.)
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)
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:
ggplot(three, aes(x = value, y = set)) +
geom_boxplot(width = 0.5) +
labs(x = "value", y = NULL)
But the histograms show three completely different distributions:
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")
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:
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")
tapply() applies a function to each group separately:
tapply(InsectSprays$count, InsectSprays$spray, median)
tapply(InsectSprays$count, InsectSprays$spray, IQR)
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.)
Subtract the mean, then divide by the standard deviation. The answer is negative: the baby is below average.
A dataset has and . Above what value is an observation flagged as a possible outlier?
Find the IQR, multiply by 1.5, and add it to .
Where are the values more spread out: below the median or above it? The long tail is on that side.
Can a boxplot show two peaks at all? Look back at Example 2.11.
The upper half of the data is more spread out than the lower half, so the long tail is on the right: right-skewed.
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 measures position in standard deviations; it doesn't depend on units.
- Under : the mean becomes , the SD becomes .
- 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 |
| 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 |
| 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 ; 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.
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")
WinF WinNF Veh Con Tabl Head
70 76 17 13 9 29
The modal category is WinNF (building window, non-float), with 76 fragments, just ahead of WinF with 70. Together, building windows make up
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.
ggplot(airquality, aes(x = Temp, y = Ozone)) +
geom_point(alpha = 0.7, na.rm = TRUE) +
labs(x = "maximum temperature (°F)", y = "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 . They're in R as anscombe. Compute the mean and standard deviation of each and , and the correlation (Chapter 6) between them. Then plot them.
sapply() applies a function to every column of a data frame:
sapply(anscombe, mean)
sapply(anscombe, sd)
sapply(1:4, function(i) cor(anscombe[[i]], anscombe[[i + 4]]))
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 has mean 9 and standard deviation 3.32; every has mean 7.50 and standard deviation 2.03; every correlation is 0.82. By the numbers, the four datasets are identical. Now look:
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)
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 creates the whole correlation. A prediction for a new 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:
- points curving upwards at the right end (and often at the left): the largest values are too large, a sign of right skew;
- points curving downwards at the left end: the smallest values are too small, left skew;
- an S shape, with both ends pulling away from the line in opposite directions: heavy tails (more extreme values at both ends than a bell would produce).
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?
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")
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.
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
The variable is measured repeatedly over time. Which picture connects points in time order?
A line graph shows change over time; joining the points in order makes trends and seasonal patterns visible.
One numerical variable (refractive index) and one categorical variable (type) that splits it into groups.
Side-by-side boxplots compare a numerical variable across groups on a common axis. A single histogram would mix the groups together, and a bar chart or pie chart is for a categorical variable on its own.
The summaries are correct for all four datasets. Are they useless, or just incomplete?
Correlation is fine for dataset 1. What went wrong for the others, and how would you have noticed?
Summaries compress the data and lose information. They're useful, but only alongside a picture that shows whether they describe the data sensibly.
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.
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
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
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:
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)
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.
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:
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 : It is 0 when one category has everything (no uncertainty), and as large as possible, , when all 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,
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
[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.
Remember Berkeley. Could the hospitals differ in which patients they treat?
Equal totals don't mean equal mixes of patients. What third variable affects both which hospital and survival?
Severity affects both the hospital a patient goes to and their chance of survival: a confounder. A fair comparison looks at survival within severity groups. It's quite possible that B does better for both mild and severe cases, and looks worse overall only because it treats so many severe ones.
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.
- Prediction. The mean, median and mode are the best single predictions under squared, absolute and zero–one loss. The standard deviation and IQR measure how wrong such a prediction is likely to be. Scatterplots show when one variable can help predict another (temperature and ozone).
- Inference. Pictures and summaries are where we first notice that a mechanism might be at work: two peaks in Old Faithful's eruptions pointed to two eruption types; side-by-side boxplots suggested some insecticides work better than others; a systematic gap between Michelson's results and the truth revealed bias in his apparatus. Simpson's paradox showed that a pattern in pooled data can mislead about the mechanism, which is why inference needs the causal thinking of Chapter 1.
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
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 ofwaitingagainsteruptions, 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, puteruptionson 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.
Mean, median and skew. For the
islandsdataset (areas of the world's major landmasses, in thousands of square miles), compute the mean and median. Explain the difference. Then repeat forlog(islands).mean(islands),median(islands). Drawhist(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.
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
and . For the SD, follow the six-step algorithm in Section 2.3; the deviations from the mean are . Mean 13; median 11.5; squared deviations 16, 9, 4, 1, 1, 81 sum to 112, so
and minutes. , , IQR . Upper fence , so the examiner who took 22 minutes is a possible outlier. 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 minutes, so and in .
Mean
seconds; SD seconds. Multiplying every value by multiplies both the mean and the SD by (here ). 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 ismean(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.
Glass. Using
fgl, draw side-by-side boxplots of refractive index (RI) by glasstype. 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.
Michelson revisited. Using
morley, compute the mean and standard deviation of each experiment separately withtapply(). 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).
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.
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 usemargin.table()andprop.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.
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 similarlyswithsd. Thenplot(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.