Probability and Statistics · Chapter 1

Chapter 1
Prediction, inference and data

Lectures 1–2 · why we collect data, how we collect it, and why that decides what it can tell us

Cartoon: a forecastA weather forecaster stands beside a board showing a cloud and the number 70 percent and says: 70% chance of rain tomorrow. A second person asks: So will it rain or not? 70%70% chance of raintomorrow.So... will itrain or not?
useful predictions come with their uncertainty attached

Count the predictions that touched your life today. Your phone guessed the next word you would type. A streaming service guessed what you'd want to watch. A fast-food app offered you a deal it predicted would bring you back this week. Somewhere, an airline sold more tickets for your flight than the plane has seats, predicting that some passengers wouldn't show up.

None of these systems can see the future. Each one found a pattern in past data and bet that the pattern would continue. And each one was designed knowing it would sometimes be wrong: the deal you ignore, the word you delete, the passenger who has to be bumped. The goal is never to be right every time. It is to keep the cost of being wrong at a level everyone can live with.

That, in one sentence, is what statistics is for. This chapter sets up the whole course: what prediction and inference are, where data come from, and why the way data are collected decides what they can and cannot tell you.

There is very little mathematics in this chapter, and that is deliberate. The ideas here are the ones that decide whether a calculation means anything at all. A perfectly computed average of badly collected data is still a bad answer, and no formula later in the course can rescue it. So read this chapter the way a detective reads a crime scene: before asking what the numbers say, ask where the numbers came from.

Here is the route through the chapter.

Think About It: Before You Start

Think of one decision you made this week that depended on a prediction: when to leave for class, whether to take an umbrella, which line to join at the supermarket. What information did you use? What would it have cost you to be wrong in each direction? Keep your example in mind as you read Section 1.1, and see whether it fits the pattern described there.

Lecture 1 — Prediction, inference and sampling

1.1 Predicting under uncertainty

The seat that isn't empty

Airlines know that some ticket holders don't show up. Fly with empty seats and you lose money you could have earned. So they sell a few more tickets than there are seats. Sell too many, and more people show up than can fit: someone is bumped, and the airline pays compensation (and gets bad press). The airline must decide today how many tickets to sell, without knowing who will turn up.

Two things make this decision possible:

  1. A pattern. From years of past flights, the airline knows roughly what fraction of ticket holders show up.
  2. A cost for each kind of mistake. An empty seat costs one lost fare. A bumped passenger costs compensation, a hotel, perhaps a lost customer.

With those two ingredients, the airline can choose the number of tickets that keeps the average cost of its mistakes as small as possible. Try it.

How many tickets should the airline sell?

A plane has 100 seats. Every ticket holder independently shows up with the same probability. Choose how many tickets to sell and what each kind of mistake costs. The top panel shows how likely each number of show-ups is: orange bars are flights where someone gets bumped. The bottom panel shows the average cost of the mistakes for every number of tickets you could sell. Find the number that keeps the errors cheapest, then fly some flights.

TopTop: bar chart of the probability of each number of passengers showing up, with bars above 100 highlighted. Bottom: average cost of empty seats and bumped passengers against the number of tickets sold, with the minimum marked.

Notice three things.

Think About It: Whose Costs?

In the widget, you chose what an empty seat and a bump cost. In real life, who decides those numbers? The airline counts a bump as a compensation payment; the bumped passenger counts a missed wedding or job interview. If the airline used the passenger's costs instead of its own, would it sell more tickets or fewer? Whenever someone tells you a prediction rule is "optimal", it is worth asking: optimal for whom?

The passenger's cost of being bumped is usually much larger than the compensation the airline pays, so with the passenger's costs the bump would be more expensive and the best number of tickets would go down. "Optimal" always means optimal for a particular choice of loss, and somebody chose it. Regulations (such as compulsory compensation for bumped passengers) are partly a way of making a company's costs closer to the public's.

The same structure is everywhere. A pharmacy predicts how many doses of a vaccine to stock. A hospital predicts how many nurses it needs on a Friday night. A forensic lab predicts how long its backlog of DNA samples will take to clear. In every case there is a pattern learned from data, an unknown future, and a cost for each way of being wrong.

Definition: Prediction and Loss

A prediction rule is a function f that takes information we have, x, and returns a guess f(x) for a quantity y that we don't know yet.

A loss function L(y,ŷ)≥0 gives the cost of guessing ŷ when the truth turns out to be y. It is 0 when the guess is perfect.

A good prediction rule is one whose loss is small on average, over the situations in which it will be used.

The definition has three ingredients, and it helps to name them in the airline story.

For instance, with cE=$250 and cB=$1000, a flight on which 97 people show up costs 3×$250=$750, and a flight on which 102 show up costs 2×$1000=$2000. The loss is lopsided: being two over is much worse than being three under. That lopsidedness is exactly why the best number of tickets is not simply "whatever makes the average turnout equal 100". We will make "small on average" precise in Chapter 4, where it becomes the expected value of the loss.

Example 1.1: How Many Tickets? ★ lecture example

A regional airline flies a 100-seat plane. Past records suggest each ticket holder shows up with probability about 0.9, independently of the others. The airline is considering selling 110 tickets.

  1. On average, how many passengers will show up?
  2. Use a computer simulation of 10,000 flights to estimate how often someone is bumped, the average number of empty seats, and the average number of bumped passengers.
  3. Is 110 a good number of tickets? What else would you need to know?

Reading the problem. Before computing anything, pick out the pieces. The unknown is the number of passengers who show up on a given flight. The information is the number of tickets (110) and the show-up probability (0.9). The decision is whether 110 is a sensible number to sell. Part 3 is a warning that the data alone may not settle that.

  1. Think of each ticket holder as contributing "0.9 of a passenger" on average. Adding up over 110 ticket holders, average number who show up=110×0.9=99. That sounds perfect for a 100-seat plane. But an average describes the typical flight, and it hides the flights that go wrong. On some flights only 93 people will turn up; on others, 104 will. The question is how often the second kind happens.

  2. Working out these chances exactly needs the binomial distribution (Chapter 4). For now we let R simulate the flights instead. The function rbinom (which we study properly in Chapter 4) counts how many of 110 independent passengers show up when each has probability 0.9, and does this once per flight.

R
set.seed(301)        # makes the simulation repeatable
# number who show up on each of 10,000 simulated flights
shows <- rbinom(10000, size = 110, prob = 0.9)
mean(shows)                  # average number who show up
mean(shows > 100)            # fraction with someone bumped
mean(pmax(100 - shows, 0))   # average empty seats
mean(pmax(shows - 100, 0))   # average bumped passengers
output
[1] 99.0012
[1] 0.3273
[1] 1.7871
[1] 0.7883

Each line does one job:

  • shows > 100 is TRUE on flights where someone is bumped, and mean() of a TRUE/FALSE vector is the fraction of TRUEs.
  • pmax(100 - shows, 0) is the number of empty seats on each flight: 100−shows when that's positive, and 0 otherwise. (pmax takes the larger of the two values, flight by flight.)
  • pmax(shows - 100, 0) similarly counts the bumped passengers.

The average is 99 show-ups, as we predicted. But on about a third of all flights (32.7%) more than 100 people show up and someone is bumped. On average there are about 1.8 empty seats and 0.8 bumped passengers per flight. A picture of the 10,000 flights shows where that third comes from:

R
flights <- data.frame(shows = shows, bumped = shows > 100)
ggplot(flights, aes(x = shows, fill = bumped)) +
  geom_bar() +
  geom_vline(xintercept = 100.5, linetype = "dashed") +
  scale_fill_manual(values = c("grey60", "orange"),
                    labels = c("everyone seated", "someone bumped")) +
  labs(x = "passengers who show up", y = "number of flights", fill = NULL)
Bar chart of the number of passengers who showed up on 10,000 simulated flights with 110…Bar chart of the number of passengers who showed up on 10,000 simulated flights with 110 tickets sold. The bars form a hump centred at 99, ranging from about 85 to 108. Bars above 100 are shaded orange and make up about a third of the flights. A dashed line marks the 100 seats. 0 500 1000 85 90 95 100 105 passengers who show up number of flights everyone seated someone bumped

The hump is centred at 99, but it is several passengers wide on each side. Everything to the right of the dashed line is a flight with an unhappy passenger. Selling 110 tickets puts the centre of the hump just under 100, so a large slice of it spills over.

  1. It depends on the costs. With cE=$250 and cB=$1000, the average cost per flight is $250 times the average number of empty seats plus $1000 times the average number of bumped passengers. From the simulation that is roughly 250×1.79+1000×0.79≈1240 dollars. (The exact figure, computed in Chapter 4, is $1240.) The widget above shows that, with these costs, 108 tickets keeps the average cost lowest, at about $1040 per flight, so 110 is a little too many. If instead an empty seat cost as much as a bump, the best number would rise to 111, and 110 would be a fine choice. The data tell us what will happen; only the costs can tell us what we should do.

What else would you need to know? Whether the 0.9 is right for this route and day (business flights on a Monday may differ from holiday flights); whether passengers really act independently (a family of five either all turns up or all doesn't, which makes big misses more likely); and what bumping really costs, including lost future customers.

History: There Is No Average Pilot

In the late 1940s the US Air Force was losing planes to crashes that weren't explained by mechanical failure. Cockpits had been designed in 1926 to fit the average pilot, using body measurements of hundreds of men. In 1950 the Air Force measured 4,063 pilots, and a young researcher, Gilbert Daniels, took ten of the body dimensions, such as height, chest and arm length, and asked how many pilots were close to average (roughly the middle 30% of pilots) on all ten.

The answer, published in 1952, was none. A cockpit built for the average pilot fitted nobody. The Air Force changed its approach: equipment had to be adjustable to fit pilots across a wide range of sizes. Car seats, steering wheels and airline seat designs followed the same idea. The idea of an "average man" as the model human being goes back to the 1830s and the Belgian scientist Adolphe Quetelet (Section 5.3 tells that story). Designing for the average is a prediction about one imaginary person. Designing for the variation is a prediction about everybody. This course is about the second kind.

Prediction as classification

Sometimes the quantity to predict isn't a number but a category: spam or not spam, guilty or not guilty, headlamp glass or window glass. A prediction rule for a category is called a classifier. There are now two ways to be wrong, and they rarely cost the same.

Example 1.2: Two Ways to Be Wrong

A spam filter predicts, for each incoming email, spam or not spam. Describe its two kinds of mistake. Which is worse, and how should that change the way the filter is designed?

A classifier with two categories can end up in four situations, because the prediction can be either category and so can the truth. It helps to lay them out in a table every time:

truly spam truly genuine
filter says spam correct: spam caught false alarm: genuine email hidden
filter says genuine miss: spam in your inbox correct: email delivered

The two diagonal cells are correct; the other two are the two kinds of mistake.

  • False alarm: a genuine email (a job offer, say) is sent to the spam folder. You may never see it.
  • Miss: a spam email lands in your inbox. You delete it, mildly annoyed.

For most people a false alarm is much worse. So a filter should only call something spam when the evidence is strong, accepting that some spam will slip through. A filter that wanted zero misses would have to send everything remotely suspicious to the spam folder, and you would lose real email; a filter that wanted zero false alarms would let everything through. You can't have both, so you choose a balance. A good filter isn't the one with the fewest mistakes overall. It is the one whose mistakes cost the least.

Example 1.3: Which Window Did This Glass Come from? ★ lecture example

Glass fragments are common trace evidence: on clothing after a burglary, or at the scene of a hit-and-run. In the 1980s the UK Home Office Forensic Science Service measured the chemical make-up of 214 glass fragments of known origin. The data are in R's MASS package as fgl ("forensic glass"). Each row is a fragment, with its refractive index (coded as (RI−1.518)×1000), the percentage by weight of eight chemical oxides (sodium Na, magnesium Mg, aluminium Al, silicon Si, potassium K, calcium Ca, barium Ba, iron Fe), and its type:

type source
WinF building window, float process
WinNF building window, non-float process
Veh vehicle window
Con container (bottles, jars)
Tabl tableware
Head vehicle headlamp

Suppose a fragment is found at the scene of a hit-and-run. Find a simple rule, using one measurement, that predicts whether a fragment came from a headlamp. How often is your rule wrong, and in which direction?

Plan. We want one measurement whose values are very different for headlamp glass and other glass. A good way to find it is to compare the average of each measurement across the six types and look for one where headlamps stand apart. Then we draw a picture, choose a cut-off, and count the mistakes.

First look at the data and the average of each oxide by type.

R
library(MASS)          # comes with R; contains the fgl data
dim(fgl)               # 214 fragments, 10 variables
table(fgl$type)        # how many fragments of each type
# average barium, by type
aggregate(Ba ~ type, data = fgl, FUN = mean)
output
[1] 214  10

 WinF WinNF   Veh   Con  Tabl  Head 
   70    76    17    13     9    29 
   type          Ba
1  WinF 0.012714286
2 WinNF 0.050263158
3   Veh 0.008823529
4   Con 0.187692308
5  Tabl 0.000000000
6  Head 1.040000000

Barium stands out: headlamps average about 1% barium, while every other type averages less than 0.2%. (Barium oxide is added to some specialist glasses.) A plot of every fragment shows the pattern clearly.

R
ggplot(fgl, aes(x = Ba, y = type)) +
  geom_jitter(height = 0.15, width = 0, alpha = 0.6) +
  geom_vline(xintercept = 0.2, linetype = "dashed") +
  labs(x = "barium oxide (% by weight)", y = NULL)
Strip plot of the barium content of 214 glass fragments, one row per glass typeStrip plot of the barium content of 214 glass fragments, one row per glass type. Almost all window, vehicle, container and tableware fragments have barium at or near zero. Most headlamp fragments have barium between about 0.5 and 3 percent, with three near zero. WinF WinNF Veh Con Tabl Head 0 1 2 3 barium oxide (% by weight)

So try the rule "predict headlamp if barium is above 0.2%." Compare its predictions with the truth:

R
table(predicted_headlamp = fgl$Ba > 0.2,
      actually_headlamp  = fgl$type == "Head")
output
                  actually_headlamp
predicted_headlamp FALSE TRUE
             FALSE   180    3
             TRUE      5   26

This is the same four-cell table as in Example 1.2. The rows are the rule's prediction (FALSE = "not headlamp", TRUE = "headlamp"), and the columns are the truth. Reading it cell by cell:

  • Bottom right (26): headlamp fragments the rule correctly flags.
  • Top right (3): headlamp fragments the rule misses. In the plot, these are the three headlamp dots sitting at zero barium.
  • Bottom left (5): other fragments the rule wrongly calls headlamps (false alarms). In the plot, these are the few dots right of the dashed line in the other rows.
  • Top left (180): other fragments correctly left alone.

So the rule is right 180+26214=206214≈0.963 of the time, about 96%. It is more informative to give the two error rates separately, because they answer different questions: miss rate=329≈10%,false-alarm rate=5185≈3%. "96% accurate" sounds impressive, but notice that a lazy rule that never says headlamp would be right 185/214≈86% of the time while catching nothing. Overall accuracy can hide a lot when one category is rare.

Why 0.2%? It is a judgement. Try the widget below to see what happens when you move the cut-off, and whether the best position changes when one mistake is worse than the other.

Two words of caution, which will come back again and again in this course.

  • We judged the rule on the same data we used to invent it. It will probably do a little worse on new fragments. Honest evaluation needs fresh data.
  • Which mistake is worse depends on the use. If the rule is a first screen that tells the lab which fragments to analyse more carefully, misses are worse than false alarms. If it were used as evidence in court, a false alarm (wrongly linking a fragment to a vehicle) could be very serious.

Forensic scientists combine several measurements to do much better than one, and report the strength of evidence rather than a yes/no answer. Machine learning methods for problems like this are exactly what the field of classification is about.

Where should the cut-off go?

Each dot is one of the 214 glass fragments in fgl: headlamp fragments in the top row, all other fragments in the bottom row, placed by their barium content. The rule says "headlamp" for every fragment to the right of the dashed line. Slide the line and watch the two kinds of mistake trade off against each other: misses (headlamps left of the line) and false alarms (other glass right of the line). Then say how much worse a miss is than a false alarm.

Strip plot of barium content for headlamp and non-headlamp glass fragments, with an…Strip plot of barium content for headlamp and non-headlamp glass fragments, with an adjustable cut-off line. Misses and false alarms are highlighted.
Rows: what the rule says. Columns: the truth.
headlampnot headlamp
says headlamp
says not

Three lessons from the widget are worth stating plainly. First, every cut-off makes mistakes; moving it only changes which mistakes. Second, the data limit what any rule can do: three headlamp fragments contain no barium at all, so no cut-off catches them, and once the line is left of the lowest barium-bearing headlamp (0.4%), moving it further left only adds false alarms. Third, the best cut-off depends on the relative cost as well as on the data, although here it is stable: 0.3% is cheapest unless a miss costs less than a tenth of a false alarm, and then the cheapest rule jumps to 0.7%, accepting ten more misses to avoid one false alarm. This is the same trade-off a medical screening test or a fraud filter faces, and we will meet it again as the trade-off between Type I and Type II errors in Chapter 9.

Check Yourself

A bank's software flags credit-card transactions as possibly fraudulent, using the amount, the location and your usual spending.

Which pair correctly describes its two kinds of mistake?
A fast-food app sends "$2 off" coupons to customers it predicts will come back this week only if they get one. Which mistake wastes the $2?

Key Takeaways

  • A prediction is a guess about something not yet known, made from information we have.
  • Every prediction is wrong sometimes. The aim is to make the cost of the mistakes, on average, as small as possible.
  • The best prediction depends on the data and on the costs of the different kinds of error.
  • For a classifier, lay out the four outcomes in a table. Moving a cut-off trades misses for false alarms; no cut-off removes both.
  • Judge a prediction rule on data it hasn't seen.

1.2 Inference: learning the mechanism

The comet that came back

Prediction asks what will happen? There is a deeper question: why does it happen? What is the mechanism that produced the data, and how does it work?

The universe seems to run on rules. Planets keep to their orbits, drugs act on the body in consistent ways, coins land heads about half the time no matter who flips them. The data we collect are produced by these rules, blurred by randomness. If we can learn the rule from the data, we gain something prediction alone never gives us: we can explain the past, predict the future, and predict what would happen if we changed something.

History: Halley's Comet

In 1705 the astronomer Edmond Halley studied the recorded paths of comets. He noticed that the bright comets of 1531, 1607 and 1682 had almost identical orbits, about 76 years apart. Rather than three comets, he inferred one comet on a long elliptical orbit around the Sun, obeying Newton's new law of gravitation. From that mechanism he predicted the comet would return in late 1758.

Halley died in 1742. On Christmas night of 1758 an amateur astronomer in Germany, Johann Palitzsch, saw the comet return, as predicted. The same mechanism also reached backwards: astronomers have since matched the comet to sightings going back over two thousand years, including the one stitched into the Bayeux Tapestry in 1066. Learning the mechanism explained the past and predicted the future.

Most mechanisms we study are less tidy than gravity. A drug lowers blood pressure, but by different amounts in different people. A spam filter's errors depend on what spammers try next. So we think of data as the output of a machine with two parts: a systematic part, the rule, and a random part, the noise.

A data-generating process drawn as a machineA data-generating process drawn as a machine. Inputs on the left are the systematic part, the rule, and the random part, the noise. They combine inside a box labelled mechanism. Out of the right side come the data: observation 1, observation 2, and so on.the rule(systematic)the noise(random)mechanismdatax₁, x₂, x₃, …
Data = rule + noise. Inference tries to recover the rule; prediction uses it.

Definition: Data-Generating Process

The data-generating process (DGP) is the mechanism, partly systematic and partly random, that produced the data we observe. Its unknown numerical features, such as the average effect of a drug or the fraction of fragments containing barium, are called parameters.

Statistical inference is the use of data to draw conclusions about the data-generating process, including how uncertain those conclusions are.

To make the picture concrete, here is one way to write a data-generating process for the birth weights we meet in Example 1.4: birth weight⏟what we observe=μgroup⏟rule+ε⏟noise. Here μgroup is the average birth weight for babies in a given group (say, mothers who smoked), a fixed but unknown parameter, and ε ("epsilon") is everything else that makes one baby heavier or lighter than its group's average: genes, the length of the pregnancy, luck. We never see μ or ε separately, only their sum. Inference is the art of pulling them apart using many observations: the rule is what stays the same from baby to baby, and the noise is what doesn't.

The last four words of the definition matter. A conclusion without a measure of its uncertainty is not inference, it's a guess. Here is a mechanism you can't see inside. Learn about it the only way scientists ever can: by watching what it produces.

The mystery machine

Inside this machine is a spinner with an unknown fraction of its face coloured orange. You can't open it. All you can do is spin it and record what comes out. Spin a few times and make a guess about the fraction, then keep spinning. The shaded band shows the range of fractions that are still plausible given what you've seen; watch it narrow. Only reveal the truth when you are confident.

TopTop: the latest spins as coloured squares. Bottom: the running fraction of orange spins against the number of spins, with a shaded band of plausible values and your guess as a dashed line.

The widget shows the central fact of inference. With a handful of spins, a wide range of mechanisms could have produced what you saw. As data accumulate, the plausible range narrows, but it never shrinks to a single point. Chapter 8 shows how to compute that range.

Prediction or inference?

The same data can serve both goals, but they ask different questions.

Example 1.4: Smoking and Birth Weight ★ lecture example

In 1986, Baystate Medical Center in Springfield, Massachusetts, recorded data on 189 births, including the baby's birth weight and whether the mother smoked during pregnancy. The data are in R as MASS::birthwt (from Hosmer and Lemeshow's book Applied Logistic Regression). Low birth weight (below 2,500 g) is linked to serious health problems for the baby.

  1. Compare the average birth weight of babies born to mothers who did and didn't smoke.
  2. Write one predictive question and one inferential question these data could help answer.
  3. Can we conclude from this comparison that smoking causes lower birth weight?
  1. In birthwt, bwt is birth weight in grams and smoke is 1 for mothers who smoked, 0 otherwise.
R
library(MASS)
table(birthwt$smoke)     # 0 = did not smoke, 1 = smoked
aggregate(bwt ~ smoke, data = birthwt, FUN = mean)
output

  0   1 
115  74 
  smoke      bwt
1     0 3055.696
2     1 2771.919
R
bw <- birthwt
bw$smoker <- factor(bw$smoke, labels = c("did not smoke", "smoked"))
ggplot(bw, aes(x = smoker, y = bwt)) +
  geom_boxplot(outlier.shape = NA, width = 0.5) +
  geom_jitter(width = 0.12, alpha = 0.5) +
  labs(x = "mother during pregnancy", y = "birth weight (g)")
Birth weights of 189 babies, plotted as dots in two columnsBirth weights of 189 babies, plotted as dots in two columns: mothers who did not smoke and mothers who smoked. A box marks the middle half of each group. The smokers' group sits lower, with its middle around 2,800 grams compared with about 3,100 grams for non-smokers, but the two groups overlap a great deal. 1000 2000 3000 4000 5000 did not smoke smoked mother during pregnancy birth weight (g)

The table shows 115 non-smokers and 74 smokers. The averages are 3,055.7 g and 2,771.9 g, so babies of mothers who smoked were 3055.7−2771.9=283.8≈284 g lighter on average, roughly 10% of a typical birth weight. In the plot, each dot is one baby; the box covers the middle half of each group and the line inside it marks the middle value (Chapter 2 explains boxplots in detail). Notice how much the groups overlap: plenty of smokers had heavier babies than plenty of non-smokers. The difference is in the averages, not in every individual.

  1. Two possible questions:

    • Predictive: "Given what we know about a pregnant patient, how likely is her baby to be born below 2,500 g?" A hospital could use the answer to decide who needs extra monitoring. It doesn't matter why the prediction works, only that it is accurate.
    • Inferential: "In the population of all such pregnancies, how large is the difference in average birth weight between smokers and non-smokers, and how sure can we be?" Here we want a number describing the mechanism, with a margin of error.
  2. Not from this comparison alone. Mothers who smoked may differ from those who didn't in other ways (income, stress, diet, access to care) that also affect birth weight. The 284 g could be partly or even wholly due to those differences. Section 1.5 shows how to think about this. (From many other studies, including some cleverly designed ones, we do know that smoking during pregnancy reduces birth weight. But this dataset alone can't establish it.)

There is a third kind of question, the most ambitious of all.

Definition: Three Kinds of Question

  • A descriptive question asks what the data show: How many fragments contain barium?
  • A predictive question asks what an unseen outcome will be: Will this patient's baby be born underweight?
  • An inferential question asks about the data-generating process: What is the average birth weight in the population, and how sure are we? A causal question is an inferential question about what would happen if we intervened: How much heavier would babies be if mothers stopped smoking?

Example 1.5: What Kind of Question Is It?

Classify each question as descriptive, predictive, inferential, or causal.

  1. What fraction of the 214 glass fragments in fgl came from headlamps?
  2. Will the next email in my inbox be spam?
  3. Do police body cameras reduce complaints against officers?
  4. What is the average lead level in the drinking water of all NYC public schools, based on tests of 60 of them?
  5. Which patients arriving at an emergency room are likely to need intensive care in the next 24 hours?
  6. Would lowering the speed limit to 25 mph reduce pedestrian deaths in NYC?
  1. Descriptive: count and report; no uncertainty about these 214 fragments.
  2. Predictive: a guess about one unseen outcome.
  3. Causal: what happens because of the cameras.
  4. Inferential: from 60 schools to all of them, with a margin of error.
  5. Predictive: it doesn't matter why a patient is at risk, only that we identify them.
  6. Causal: what would happen if we intervened.

Some words are useful clues, though never a substitute for thinking:

clue in the question usually signals
"how many", "what fraction of these" descriptive
"will", "which ... is likely to", "the next" predictive
"all", "in general", "the population", "how sure" inferential
"cause", "effect", "reduce", "if we changed", "would" causal

Question 4 is the subtle one. The 60 tested schools could be described exactly, but the question asks about all schools, and that leap from a part to the whole is what makes it inferential.

Think About It: The Same Data, Different Questions

A hospital has records of 10,000 past emergency-room patients: their symptoms on arrival, their age, which treatment they received, and whether they needed intensive care. Write one descriptive, one predictive and one causal question these records could be used for. Which of your three questions do you think the records can answer most reliably, and which least? Why?

For example: descriptive, "what fraction of these patients needed intensive care?"; predictive, "will the patient who has just arrived need intensive care?"; causal, "does treatment A reduce the need for intensive care compared with treatment B?". The descriptive question is answered exactly by counting. The predictive question can be answered reasonably well if future patients resemble past ones. The causal question is the hardest: doctors chose the treatments, probably giving the stronger treatment to sicker patients, so a comparison of outcomes mixes the treatment's effect with how sick the patients were. Section 1.5 shows why this matters.

Bayesian Inference: Two Ways to Be Uncertain About a Mechanism

In the mystery machine, the true fraction of orange is a fixed number we don't know. There are two schools of thought about how to express our uncertainty about it.

  • The frequentist view (the main thread of this course) treats the parameter as fixed and the data as random. It asks: how would my method behave if I repeated the experiment many times? "The plausible range" means a range produced by a method that captures the truth, say, 95% of the time.
  • The Bayesian view treats our knowledge of the parameter as uncertain and describes it with probabilities. Before spinning, you might believe any fraction is equally likely. Each spin updates that belief, and you can say things like "there is a 90% probability the fraction is between 0.3 and 0.5."

Both are used in science and industry every day, and they often give similar answers. These boxes will show you the Bayesian version of each idea as we go.

Interlude (Optional): Why Should the Future Resemble the Past?

Every prediction and every inference in this course rests on an assumption that is impossible to prove: that the mechanism which produced our data will keep working the same way. The Scottish philosopher David Hume pointed this out in the 1730s and 1740s. We have seen the sun rise every morning, but no amount of past sunrises logically proves it will rise tomorrow. This is the problem of induction.

Bertrand Russell told it as a story about a chicken. Every day of its life, the farmer arrived and fed it, so the chicken grew confident that the farmer's arrival meant food. Then one day the farmer arrived and wrung its neck.

Statistics doesn't solve Hume's problem. It makes it manageable. We assume the mechanism is stable, we say exactly what we are assuming, and we check how badly things go wrong when the assumption fails. And it does fail: in 2020, many forecasting models for travel, shopping and hospital demand broke overnight when the pandemic changed the mechanism behind the data. A model is only as good as the stability of the world it was trained on. Remember the chicken.

Key Takeaways

  • The data-generating process is the mechanism, rule plus noise, behind the data; its unknown numbers are parameters.
  • Inference learns about the mechanism from data, with a statement of uncertainty.
  • Prediction cares whether a guess is accurate; inference cares what the mechanism is; causal inference asks what would happen if we intervened.
  • With more data the plausible range for a parameter narrows, but never to a single point.

1.3 Populations, samples and how we choose them

We can't measure everything

A police department seizes 2,000 small bags of white powder in a raid. To charge the suspects, the lab must show the bags contain an illegal drug. Testing every bag would take weeks. Instead, the lab tests a few dozen and draws a conclusion about all 2,000.

This is the basic move of statistics: look at a part to learn about the whole. Whether it works depends almost entirely on which part we look at.

Definition: Population, Sample, Parameter, Statistic

  • The population is the entire collection of individuals (people, objects, events) we want to learn about. Its members are called units.
  • A sample is the subset of the population we actually observe. Observing every unit is a census.
  • A parameter is a number describing the population, such as the fraction of all 2,000 bags that contain cocaine. It is usually unknown.
  • A statistic is a number computed from a sample, such as the fraction of the tested bags that contain cocaine. We use statistics to estimate parameters.

A memory aid: parameter goes with population, statistic goes with sample.

Example 1.6: A Sample of the States ★ lecture example

R's USArrests dataset gives, for each of the 50 US states in 1973, the number of arrests for murder per 100,000 residents (from the World Almanac and Book of Facts 1975). Treat the 50 states as the population.

  1. Compute the population mean of the murder arrest rate. Is it a parameter or a statistic?
  2. Draw a simple random sample of 10 states and compute the sample mean. Parameter or statistic?
  3. Repeat the sampling 1,000 times. What do the 1,000 sample means tell you?
  1. Because we have all 50 states, this mean is a parameter: a fact about the whole population.
R
mean(USArrests$Murder)     # all 50 states
output
[1] 7.788
  1. sample(x, 10) picks 10 entries of x at random, every possible set of 10 being equally likely.
R
set.seed(1973)
chosen <- sample(rownames(USArrests), 10)   # 10 random states
chosen
mean(USArrests[chosen, "Murder"])            # the sample mean
output
 [1] "New Hampshire"  "Delaware"       "Mississippi"   
 [4] "Maine"          "Kentucky"       "North Carolina"
 [7] "West Virginia"  "New York"       "Iowa"          
[10] "Rhode Island"  
[1] 7.13

The sample mean, 7.13, is a statistic. It's near the true value, 7.788, but not equal to it. A different sample would give a different number.

  1. replicate repeats a calculation many times.
R
means <- replicate(1000, mean(sample(USArrests$Murder, 10)))
mean(means)    # the average of the 1,000 sample means
sd(means)      # how much they typically vary (Chapter 2)
output
[1] 7.80708
[1] 1.223097

The line replicate(1000, mean(sample(USArrests$Murder, 10))) reads from the inside out: draw 10 random states' rates, average them, and do the whole thing 1,000 times, keeping the 1,000 averages. A histogram shows how they spread out:

R
ggplot(data.frame(means), aes(x = means)) +
  geom_histogram(binwidth = 0.4, colour = "white") +
  geom_vline(xintercept = mean(USArrests$Murder), linetype = "dashed") +
  labs(x = "sample mean of 10 states (murder arrests per 100,000)",
       y = "number of samples")
Histogram of 1,000 sample means, each from a random sample of 10 statesHistogram of 1,000 sample means, each from a random sample of 10 states. The histogram is a hump centred near 7.8, ranging from about 4 to 11.7. A dashed vertical line marks the true population mean of 7.788, at the centre of the hump. 0 50 100 4 6 8 10 12 sample mean of 10 states (murder arrests per 100,000) number of samples

Two features of this picture are worth remembering, because they are the two halves of the story of sampling.

  • The centre is in the right place. The 1,000 sample means average 7.81, very close to the true 7.788 (the dashed line). Random samples are not systematically too high or too low; they are right on average.
  • The spread is not zero. Individual sample means range from about 4 to almost 12, and typically miss the truth by around 1.2. Any one sample can be unlucky.

A statistic is a random quantity: it changes from sample to sample, but in a pattern we can predict and measure. Chapter 7 is about exactly this pattern, and Chapter 8 uses it to put a margin of error on a single sample's answer.

Choosing the sample

The simplest fair method treats every unit identically.

Definition: Simple Random Sample

A simple random sample (SRS) of size n from a population of N units is chosen so that every possible set of n units is equally likely to be the sample.

Drawing names from a well-shaken hat produces a simple random sample. So does R's sample() function. One consequence is the fairness property we want:

Theorem: Every Unit Has the Same Chance

In a simple random sample of size n from a population of N units, every unit has the same probability, n/N, of being included.

Idea. Count, in two different ways, how many (unit, sample) pairs there are with the unit belonging to the sample.

List every possible sample of size n; say there are M of them, all equally likely. The definition of an SRS treats all units the same way, so by symmetry every unit appears in the same number of these samples; call that number k.

Now count the pairs (unit, sample containing it).

  • Sample by sample: each of the M samples contains n units, giving nM pairs.
  • Unit by unit: each of the N units lies in k samples, giving Nk pairs.

Both counts describe the same collection of pairs, so Nk=nM⇒kM=nN. A particular unit is included exactly when the sample drawn is one of the k samples that contain it. All M samples are equally likely, so the probability of inclusion is the number of samples containing the unit divided by the number of possible samples: Pr(unit is included)=kM=nN.◼∎

A tiny case makes the theorem concrete. Take a population of N=4 units, {A,B,C,D}, and a simple random sample of n=2. The possible samples are {A,B},{A,C},{A,D},{B,C},{B,D},{C,D}, so M=6, each with probability 1/6. Unit A appears in k=3 of them, as does every other unit, so each unit is included with probability 3/6=1/2=n/N. Check the double count: nM=2×6=12 and Nk=4×3=12.

The theorem says every unit has the same chance. That's necessary for a fair sample but not enough on its own: for a list of 20 units, a method that tosses a coin to pick either the first 10 or the last 10 also gives every unit a 50% chance, but it never picks a mix. A simple random sample makes every combination equally likely, which is a much stronger guarantee.

Other designs are often more practical:

Definition: Sampling Bias

A sampling method is biased if it systematically favours some parts of the population over others, in a way related to what is being measured, so that its statistics tend to be too high or too low for the parameter. Bias is a property of the method, not of one particular sample, and taking a bigger sample does not fix it.

See this for yourself. A researcher in New York who wants a quick estimate might only collect data from nearby states.

Sampling the fifty states

The population is all 50 US states, and the variable is each state's 1973 murder arrest rate per 100,000 residents (R's USArrests data). Because we know every value, we know the true average of the 50 rates: 7.788. Pretend we don't, and estimate it from a sample. A simple random sample gives every state the same chance. A stratified sample takes a random sample from each of the four regions, roughly in proportion to its size, and weights each region’s average by that region’s share of the 50 states. A convenience sample uses only the states closest to New York: the Northeast. Draw many samples with each method and compare where the estimates land.

TopTop: the 50 states as labelled dots by murder arrest rate, in four rows by region, with the states in the latest sample highlighted. Bottom: one strip per sampling method showing the sample averages from repeated samples, with a vertical line at the true average 7.788.

Watch two things as you draw more samples: where each method's estimates are centred, and how spread out they are. The convenience estimates cluster tightly, around 4.7, far from the truth of 7.788. In 1973 the Northeast had lower murder arrest rates than the South, so a sample drawn only from the Northeast is biased, however carefully it's drawn. Random and stratified samples land around the truth; the stratified samples vary a little less, because they never get unlucky and miss a whole region.

Think About It: Precise But Wrong

In the widget, the convenience sample's estimates were less spread out than the random sample's, yet much further from the truth. Explain how a method can be very consistent and still be wrong. Can you think of an everyday measuring device with the same problem?

Consistency (small spread) and correctness (being centred on the truth) are different properties. The Northeast states all have similar, low rates, so every convenience sample gives nearly the same answer, but it is the answer to a different question ("what is the rate in the Northeast?"). A bathroom scale that always reads 2 kg light is the everyday version: weigh yourself ten times and you get the same number every time, precisely wrong. In Chapter 8 these two properties get names, bias and variance, and we will see that good estimators need both to be small.

The same two ideas can be drawn as darts thrown at a target, where the bullseye is the true value and each dart is the estimate from one sample:

Four dartboards in a two-by-two gridFour dartboards in a two-by-two grid. Top left, low bias and low variance: the darts are tightly grouped on the bullseye. Top right, low bias and high variance: the darts are scattered widely but centred on the bullseye. Bottom left, high bias and low variance: the darts are tightly grouped, but up and to the right of the bullseye. Bottom right, high bias and high variance: the darts are scattered widely around a point away from the bullseye. A cross on each board marks the average of its darts.low bias, low variancelow bias, high variancehigh bias, low variancehigh bias, high variancebullseye = true value θ; dots = estimates from different samples; × = their average
Bias is aiming at the wrong place (the average of the darts is off-centre); variance is a shaky hand (the darts are spread out). Only the top-left estimator is both accurate and precise.

History: The Poll That Ended a Magazine

In 1936 the Literary Digest, a popular American magazine, conducted the largest poll in history. It mailed about 10 million ballots, using lists of its own readers, telephone owners and car registrations, and received about 2.4 million back. It predicted that the Republican Alf Landon would beat President Franklin Roosevelt, with about 57% of the vote.

Roosevelt won with about 61% and carried 46 of the 48 states. Meanwhile, a young pollster named George Gallup predicted a Roosevelt win using a sample of around 50,000.

What went wrong? In the middle of the Great Depression, people who owned phones and cars and subscribed to magazines were richer than average, and richer voters leaned Republican. And of the 10 million, only a quarter replied, and those who replied were not typical of those who didn't. A sample of 2.4 million, collected with a biased method, lost to one fifty times smaller collected with a better one. The Digest closed within two years.

Causal Inference: Who Ends Up in the Sample?

Sampling bias is a causal problem in disguise. Ask: what causes a unit to end up in the sample? In the 1936 poll, wealth caused people to be on the mailing lists, and wealth also affected how they voted. Whenever the thing that puts units into your sample is connected to the thing you're measuring, your sample is biased. Random sampling works because nothing about the unit causes it to be chosen: a random number generator decides. We will draw this as a diagram in Section 1.5.

Example 1.7: Naming the Parts

For each study, identify the population, the sample, the parameter of interest and the statistic used to estimate it. Then say whether the sampling method could be biased, and how.

  1. A crime lab receives 2,000 seized bags. It tests a simple random sample of 40 and finds that 38 contain cocaine.
  2. A software company wants to know the average page-load time its users experience. It measures load times on 500 visits from computers in its own office.
  3. A toxicologist estimates the average mercury level in tuna sold in NYC by buying one can from each of 25 randomly chosen supermarkets.
  1. Population: the 2,000 bags. Sample: the 40 tested. Parameter: the fraction of all 2,000 bags containing cocaine. Statistic: 38/40=0.95. A simple random sample is not biased. (Whether 40 bags is enough is a separate question, about precision; Chapter 8.)
  2. Population: all visits by all users. Sample: 500 visits from the office. Parameter: the average load time over all user visits. Statistic: the average of the 500. Biased: office computers probably have fast connections close to the company's servers, so the sample underestimates what typical users experience. Measuring 5,000 office visits would not help.
  3. Population: all cans of tuna on sale in NYC. Sample: 25 cans. Parameter: the average mercury level per can. Statistic: the average of the 25. This is a two-stage design (random stores, then one can from each). It's reasonable if stores are chosen randomly, but one can per store can't show how much cans vary within a store, and it ignores small shops, corner stores and online sales, which might stock different brands.

Example 1.8: The Average of the States Is Not the Average American

In Example 1.6 the average of the 50 state murder arrest rates was 7.788 per 100,000. Is this the murder arrest rate for the United States as a whole?

No. Each state counts once in an average of the 50 rates, whether it has 400,000 people (Wyoming) or 21 million (California). The national rate counts each person once, so big states should count more. R's state.x77 data include each state's population in 1975 (in thousands), which is close enough to weight by:

R
weighted.mean(USArrests$Murder, w = state.x77[, "Population"])
output
[1] 9.225131

A weighted mean gives each value xi a weight wi and computes x‾w=w1x1+w2x2+⋯+wnxnw1+w2+⋯+wn=∑i=1nwixi∑i=1nwi. To see why it matters, imagine just two states: a big one with 9 million people and a rate of 12, and a small one with 1 million people and a rate of 2. The ordinary average of the two rates is (12+2)/2=7. But 9 of the 10 million people live in the high-rate state, and the rate across all 10 million people is x‾w=9×12+1×29+1=11010=11. The weighted mean is pulled towards the big state, because that is where most of the people are.

Back to the real data. Weighted by population, the rate is about 9.2 per 100,000, noticeably higher than 7.788: several of the most populous states (California, Texas, New York, Florida, Illinois, Michigan) had rates above the state average. Neither number is "wrong". They answer different questions, about states and about people. Always ask what the units are.

Check Yourself

A news website runs a poll: "Should NYC ban cars below 60th Street? Click to vote!" 12,000 people vote, and 71% say yes.

Which statement is correct?

Key Takeaways

  • A population is everything we want to know about; a sample is the part we observe.
  • Parameters describe populations and are usually unknown; statistics describe samples and estimate parameters.
  • A simple random sample makes every set of n units equally likely; every unit then has chance n/N.
  • Bias comes from the method, not the sample size. A large biased sample is still biased.
  • Always ask what the units are: an average over states is not an average over people.

Lecture 2 — Variables, studies and independence

1.4 Variables, data and measurement

Once we have a sample, we measure things about each unit. Data almost always arrive as a table: one row per unit, one column per measurement. Statisticians call this shape tidy data, and R stores it as a data frame (Section 0.5).

Definition: Variables and Their Types

A variable is a characteristic recorded for each unit; its value can vary from unit to unit. Variables come in two main types.

  • A categorical variable places each unit in a group.
    • It is nominal if the groups have no natural order (glass type; blood type).
    • It is ordinal if they do (pain on a scale of mild, moderate, severe; a letter grade).
  • A numerical (quantitative) variable is a number for which arithmetic makes sense.
    • It is discrete if its possible values can be listed, usually counts (number of arrests; number of previous premature labours).
    • It is continuous if it can take any value in an interval, usually measurements (birth weight; refractive index; time).

A quick test sorts most variables. Ask two questions in turn.

  1. Does arithmetic make sense? If "the average value" means something, the variable is numerical. If the values are labels (even labels written as numbers, like a jersey number or a ZIP code), it is categorical.
  2. If categorical: is there a natural order? Then ordinal, otherwise nominal. If numerical: can you list the possible values, with gaps between them? Then discrete, otherwise continuous.

The type of a variable decides which summaries and plots make sense (Chapter 2) and which probability models fit it (Chapters 4 and 5). An average ZIP code, or a histogram of blood types, is a sign that someone skipped this step. Getting it right is the first step of every analysis.

FigureFigurevariablecategoricallabels or groupsnumericalarithmetic makes sensenominalno orderordinalordereddiscretecountablecontinuousany valueglass type,blood typepain level,letter gradenumber ofarrestsbirth weight,refractive index
Two questions sort most variables: does arithmetic make sense? Then, is there an order (categorical), or can the values be listed with gaps (numerical)?

Example 1.9: What Kind of Variable Is It? ★ lecture example

Look at the structure of the birth weight data, then classify each variable. Is R treating every variable correctly?

R
str(birthwt)
output
'data.frame':    189 obs. of  10 variables:
 $ low  : int  0 0 0 0 0 0 0 0 0 0 ...
 $ age  : int  19 33 20 21 18 21 22 17 29 26 ...
 $ lwt  : int  182 155 105 108 107 124 118 103 123 113 ...
 $ race : int  2 3 1 1 1 3 1 3 1 1 ...
 $ smoke: int  0 0 1 1 1 0 0 0 1 1 ...
 $ ptl  : int  0 0 0 0 0 0 0 0 0 0 ...
 $ ht   : int  0 0 0 0 0 0 0 0 0 0 ...
 $ ui   : int  1 0 0 1 1 0 0 0 0 0 ...
 $ ftv  : int  0 3 1 2 0 0 1 1 1 0 ...
 $ bwt  : int  2523 2551 2557 2594 2600 2622 2637 2637 2663 2665 ...

The documentation (?birthwt) explains each column. Classifying them:

variable meaning type
low birth weight below 2.5 kg (1 = yes) categorical (two groups)
age mother's age in years numerical, discrete as recorded
lwt mother's weight (pounds) at last menstrual period numerical, continuous
race mother's race (1 = white, 2 = black, 3 = other) categorical, nominal
smoke smoked during pregnancy (1 = yes) categorical (two groups)
ptl number of previous premature labours numerical, discrete
ht history of hypertension (1 = yes) categorical (two groups)
ui uterine irritability (1 = yes) categorical (two groups)
ftv doctor visits in the first trimester numerical, discrete
bwt birth weight in grams numerical, continuous

R stores every column as an integer (int), because every value was coded as a number. But race is not numerical: the codes 1, 2, 3 are labels, and "the average race is 1.85" is meaningless. Tell R it's categorical by converting it to a factor:

R
mean(birthwt$race)    # R computes this, but it is nonsense
birthwt$race <- factor(birthwt$race,
                       labels = c("white", "black", "other"))
table(birthwt$race)
output
[1] 1.846561

white black other 
   96    26    67 

Age is a curious case: it's continuous in reality (you age every second), but it was recorded in whole years. How a variable is recorded can differ from what it is, and that matters later when we choose models.

A caution about the race variable itself. Race is a social category, not a biological cause. When it is associated with birth weight, that usually reflects differences in income, stress, discrimination and access to care. Section 1.5 gives a way to think about this.

Definition: Distribution of a Variable

The distribution of a variable is the pattern of its values: which values occur, and how often.

The distribution is the central object of the whole course. In Chapter 2 we describe the distribution of a sample with summaries and pictures; from Chapter 3 on we describe the distribution of a population with probability.

Check Yourself

Classify each variable. The dropdowns check as soon as you choose.

Example 1.10: What Does the Number Actually Measure?

USArrests records arrests for murder per 100,000 residents in 1973. R's state.x77 data also has a Murder column: the rate of murders and non-negligent manslaughters per 100,000 residents in 1976. Compare the two. Is either one "the murder rate"?

R
both <- data.frame(arrests_1973 = USArrests$Murder,
                   offences_1976 = state.x77[, "Murder"],
                   row.names = state.abb)
head(both)
# how closely they agree (correlation, Chapter 6)
cor(both$arrests_1973, both$offences_1976)
output
   arrests_1973 offences_1976
AL         13.2          15.1
AK         10.0          11.3
AZ          8.1           7.8
AR          8.8          10.1
CA          9.0          10.3
CO          7.9           6.8
[1] 0.9336909

A scatterplot puts one measure on each axis, with one dot per state:

R
ggplot(both, aes(x = arrests_1973, y = offences_1976)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
  geom_point() +
  labs(x = "murder arrests per 100,000 (1973)",
       y = "murders per 100,000 (1976)")
Scatterplot of 50 statesScatterplot of 50 states: murder arrests per 100,000 in 1973 on the horizontal axis against murders per 100,000 in 1976 on the vertical axis. The points rise steadily from the lower left (around 1 and 1.5) to the upper right (around 17 and 14), lying close to a dashed diagonal line where the two measures would be equal. 4 8 12 0 5 10 15 murder arrests per 100,000 (1973) murders per 100,000 (1976)

The dashed line marks where the two numbers would be equal. The states lie close to it, rising together from bottom left to top right. The two measures agree closely (a correlation of 0.93, on a scale where 1 means perfect agreement), but they are different variables. One counts arrests, which depend on how many crimes there were and on how police work: how many cases are solved, how many people are arrested per case. The other counts offences known to police. Neither counts murders that were never discovered. And they come from different years.

Every number in a dataset is the result of a measurement process, and that process has its own mechanism. Before analysing any variable, ask what exactly was measured, by whom, and what would make it go up or down apart from the thing you care about.

Think About It: Measuring the Invisible

A city reports that burglaries fell by 20% after a new policing strategy started. List at least two ways the measurement of burglary could have changed, even if the true number of burglaries didn't. What extra information would you want before believing the 20%?

Reported burglaries depend on people reporting them and on police recording them. If people lost trust in the police, or if insurance rules changed so that victims no longer needed a police report, reports would fall. If police were under pressure to show improvement, borderline cases might be recorded as "theft" or "criminal damage" instead. You would want independent evidence that doesn't run through the same recording process, such as a victimization survey that asks a random sample of households directly, and figures for similar cities that didn't change strategy.

Interlude (Optional): What Does It Mean to Measure Something?

To measure is to attach numbers to things so that relationships between the numbers mirror relationships between the things. A ruler works because if rod A is longer than rod B, A's number is bigger. The psychologist S. S. Stevens argued in 1946 that this is why the type of variable matters. Some measurements only preserve categories (nominal), some preserve order (ordinal), some preserve differences (temperature in °F: 80° is 10° warmer than 70°, but not "8/7 as hot"), and some preserve ratios (weight: 2 kg really is twice 1 kg). Arithmetic that doesn't respect the structure produces numbers that mean nothing, like the average race code above.

Even the most basic units are human decisions. Since 1983, the metre has been defined as the distance light travels in 1/299,792,458 of a second. We chose to fix the speed of light and measure length with it.

And no measurement is perfect. Every reading of a refractive index, a blood alcohol level or a DNA concentration is the true value plus some measurement error. Forensic labs spend a great deal of effort estimating exactly how large that error is, because a conviction can hinge on whether a reading of 0.081 really means "above 0.08." Measurement error is noise in the data-generating process, and much of this course is about reasoning through it.

Even famous datasets contain mistakes. R's own documentation for USArrests notes a transcription error in Maryland's urban population figure, found decades after the data were published.

Key Takeaways

  • Data come as a table: one row per unit, one column per variable.
  • Variables are categorical (nominal or ordinal) or numerical (discrete or continuous). The type decides which summaries, plots and models make sense.
  • Numbers used as labels are categorical: convert them to factors in R.
  • The distribution of a variable is the pattern of its values.
  • Every variable comes from a measurement process: ask what was really measured.

1.5 Where data come from: experiments, observation and causes

Association is not causation, and why

In Example 1.4 the babies of smokers were 284 g lighter on average. Does smoking cause lower birth weight? The difficulty is that smokers and non-smokers might differ in other ways. Suppose hardship (low income, stress, poor access to prenatal care) makes a mother more likely to smoke and also lowers birth weight by itself. Then smokers' babies would be lighter on average even if smoking itself did nothing.

The clearest way to think about this is to draw what influences what.

A causal diagram with three nodesA causal diagram with three nodes. Hardship has arrows to smoking and to birth weight. Smoking has an arrow to birth weight. Hardship is a confounder: a common cause of the exposure and the outcome.hardshipsmokingbirth weighteffect we want
Hardship is a common cause of smoking and of low birth weight: a confounder.

Definition: Causal Diagram (DAG)

A directed acyclic graph (DAG) is a collection of nodes (variables) joined by arrows, with no route that follows the arrows and returns to where it started. In a causal DAG, an arrow A→B means that A directly influences B, and every common cause of two variables in the diagram is also included in it.

A confounder of the relationship between an exposure X and an outcome Y is a common cause of both: a variable with a route of arrows into X, and a route of arrows into Y that does not pass through X.

A confounder creates an association between X and Y that has nothing to do with X causing Y. The diagram shows two routes connecting smoking and birth weight: the direct arrow (the effect we want), and the back route through hardship (confounding). A simple comparison of averages mixes the two together.

A made-up example shows how strong the back route can be. Suppose, in an imaginary town, smoking has no effect at all on birth weight. Hardship lowers the average birth weight by 300 g, and mothers facing hardship are much more likely to smoke:

group smokers others average weight
hardship 60 40 2,900 g
no hardship 20 80 3,200 g

(Each group has 100 mothers; "average weight" is the average birth weight of their babies.)

Within each row, smokers and non-smokers have the same average, because smoking does nothing. Now ignore the rows and compare all smokers with all non-smokers.

Smokers' babies appear 125 g lighter, even though smoking does nothing in this town. The whole difference travelled along the back route: smokers are mostly from the hardship group, and that is why their babies are lighter. Comparing within each row (like with like) gives the right answer, zero. The widget lets you build your own version of this and watch the apparent effect appear from nowhere.

When a third variable does the talking

A simulated study of 400 pregnancies, built so that we know the truth. Hardship (low income, stress, poor access to care) makes smoking more likely and lowers birth weight by itself. Smoking also lowers birth weight directly, by the amount you choose. Compare what an observational study would see with the true effect of smoking. Then randomize: let a coin, not hardship, decide who smokes. (Of course, no one could ethically run that experiment on real mothers. That is exactly why this problem is hard.)

LeftLeft: a causal diagram with hardship pointing to smoking and to birth weight, and smoking pointing to birth weight. Right: birth weights of babies of smokers and non-smokers as dots, with group averages, and the difference compared with the true effect.

Observational studies and experiments

Definition: Observational Study and Experiment

  • In an observational study, the researcher records what happens without deciding who receives which treatment or exposure. The units choose for themselves, or circumstances choose for them.
  • In an experiment, the researcher decides who receives which treatment.
  • In a randomized experiment, the researcher uses a chance device (a coin, a random number generator) to decide. A randomized experiment comparing a treatment group with a control group is called a randomized controlled trial (RCT).

Why does randomization matter so much? Because a coin can't be influenced by anything about the person.

Theorem: Randomization Breaks Confounding

Suppose each unit is assigned to treatment or control by a chance device whose outcome does not depend on any characteristic of the unit. Then treatment assignment is independent of every characteristic the units had before treatment, measured or not. In particular, with large groups, the treatment and control groups have very similar distributions of every such characteristic, and a systematic difference in their outcomes can only be caused by the treatment assignment: by the treatment itself, or by people knowing who was treated. That second possibility is why good trials are blinded.

Let U be any characteristic fixed before treatment (age, income, genes, anything). The chance device decides treatment without looking at U, so for every value u, Pr(treated∣U=u)=Pr(treated). That is exactly what it means for treatment to be independent of U (Chapter 3 makes this precise). Because the device never looks at the unit at all, the same is true for the whole collection of characteristics taken together, not just one at a time. So the treated and untreated groups are random samples from the same population. They can differ only by chance, and chance differences shrink as the groups grow (Chapter 7).

So any confounder's arrow into treatment is cut: in the DAG, the only arrow into "treatment" comes from the coin. Any remaining association between treatment and outcome must flow through the arrow from treatment to outcome, or be due to chance. Chapter 9 shows how to judge whether a difference is larger than chance can explain.∎

Example 1.11: The Largest Experiment in Medical History ★ lecture example

In 1954, more than a million American schoolchildren took part in trials of Jonas Salk's new polio vaccine. Polio paralysed thousands of children every year. Two designs ran side by side in different parts of the country.

  • The observed-control design (NFIP). All second-graders whose parents consented were vaccinated. First- and third-graders were left unvaccinated, as controls.
  • The randomized, double-blind design. Among children whose parents consented, a random draw decided who got the vaccine and who got an injection of salt water (a placebo). Neither the families nor the doctors diagnosing polio knew who had received which ("double-blind").

The results, in cases of paralytic polio per 100,000 children:

Randomized, double-blind design

group children rate
vaccinated 200,000 28
placebo 200,000 71
no consent 350,000 46

Observed-control design

group children rate
vaccinated (grade 2) 225,000 25
controls (grades 1 and 3) 725,000 54
no consent (grade 2) 125,000 44
  1. In the randomized design, compare the vaccinated and placebo groups.
  2. In both designs, children whose parents refused consent had a lower polio rate than the children who received a placebo or no vaccine. Why might that be?
  3. Which design gives the more trustworthy estimate of the vaccine's effect, and why?
  1. The polio rate was 28 per 100,000 among vaccinated children and 71 per 100,000 in the placebo group: the vaccine cut the rate by about 60%. Because a coin decided who was vaccinated, the two groups were alike in every other way, so this difference measures the vaccine's effect (plus some chance variation, which is tiny with 200,000 children per group).

  2. Polio was, strangely, a disease of better-off families. Children in poorer, more crowded conditions were often exposed to the virus as babies, while still protected by their mother's antibodies, and became immune without falling ill. Children raised in cleaner conditions met the virus later, when it was more dangerous. Better-off parents were also more likely to consent to the trial. So consent was tied to family income, and income was tied to polio risk:

Two causal diagrams for the 1954 polio vaccine trialsTwo causal diagrams for the 1954 polio vaccine trials. Top, the observed-control design: family income affects both whether parents consent to vaccination and the child's risk of paralytic polio, so consent and vaccination are tangled up with income. Bottom, the randomized design: among children whose parents consented, a random draw decides vaccine or placebo, so the arrow from income into vaccination is cut.observed-control design (NFIP)family incomevaccinatedpolioconsenthygiene, exposurerandomized, double-blind designfamily incomecoin flipvaccinatedpolio
Top: in the observed-control design, family background drives both vaccination and polio risk. Bottom: randomization cuts that arrow.

Refusing consent didn't protect anyone. The no-consent families were simply different families.

  1. A bar chart of all six rates makes the comparison easier to see:
R
salk <- data.frame(
  design = rep(c("randomized", "observed control"), each = 3),
  group  = rep(c("vaccinated", "not vaccinated", "no consent"), 2),
  rate   = c(28, 71, 46, 25, 54, 44))
salk$group <- factor(salk$group, levels = c("vaccinated", "not vaccinated", "no consent"))
ggplot(salk, aes(x = group, y = rate)) +
  geom_col(width = 0.6) +
  facet_wrap(~ design) +
  scale_x_discrete(labels = c("vaccine", "no\nvaccine", "no\nconsent")) +
  labs(x = NULL, y = "polio cases per 100,000")
Bar chart of paralytic polio rates per 100,000 children in the two 1954 trial designsBar chart of paralytic polio rates per 100,000 children in the two 1954 trial designs. Randomized design: vaccinated 28, placebo 71, no consent 46. Observed-control design: vaccinated 25, controls 54, no consent 44. The vaccinated bars are lowest in both designs. observed control randomized vaccine no vaccine no consent vaccine no vaccine no consent 0 20 40 60 polio cases per 100,000

("Not vaccinated" means the placebo group in the randomized design and the grade 1 and 3 controls in the other.)

The randomized design is more trustworthy. In the observed-control design, the comparison mixes the vaccine's effect with the consent effect: the vaccinated group contains only children of consenting families, while the control group contains children of both kinds of family. Its control rate (54) is lower than the placebo rate (71), so it makes the vaccine look less effective than it was (54 to 25, instead of 71 to 28). Grade could matter too: polio rates differ with age. Randomization cut every one of these back routes at once, including ones nobody thought of.

Source: T. Francis Jr. et al. (1955), "An evaluation of the 1954 poliomyelitis vaccine trials", American Journal of Public Health 45(5), part 2; table as presented in D. Freedman, R. Pisani and R. Purves, Statistics, 4th edition (2007), chapter 1.

Think About It: Why Not Just Ask Permission?

In the randomized design, some parents agreed to the trial knowing their child might get salt water instead of the vaccine. Was it ethical to give 200,000 children a placebo when a promising vaccine existed? What would have been lost if everyone who consented had simply been vaccinated? There is no single right answer here; try to argue both sides.

Against the placebo: if the vaccine worked, some placebo children caught polio who might have been protected. In this trial, the placebo group's rate (71 per 100,000) against the vaccinated group's (28) suggests that about 86 children in a group of 200,000 got paralytic polio who might not have. For the placebo: nobody knew in 1954 whether the vaccine worked or was even safe, and the observed-control design, as we saw, gave a muddied answer. A clear answer meant the vaccine could be confidently given to millions of children the following year, and that a harmful vaccine would have been detected. Modern ethics rules allow placebo controls only when there is genuine uncertainty about which treatment is better (called equipoise) and no proven treatment is being withheld.

Causal Inference: Drawing the Diagram First

Here is the habit this course will build. Before looking at any data, draw the DAG. List the exposure and the outcome, then ask: what else causes the exposure? What else causes the outcome? Anything that causes both is a confounder, and a fair comparison must deal with it, either by randomizing (cutting its arrow) or by comparing like with like (for example, comparing smokers and non-smokers within the same income level). Some arrows shouldn't be adjusted for at all: if smoking lowers birth weight by damaging the placenta, holding placental health fixed would hide the very effect you want to measure. We'll keep drawing these diagrams in every chapter.

Example 1.12: Do Body Cameras Change Police Behaviour?

A police department lets officers volunteer to wear body cameras. After a year, the volunteers have received fewer citizen complaints than the other officers. The chief concludes that cameras reduce complaints.

  1. Draw a DAG and explain the problem.
  2. Design a better study.
  1. The officers who volunteer for cameras may already be the ones who are confident in their conduct and less likely to attract complaints. An officer's attitude then causes both camera-wearing and complaints, so it is a confounder:
A causal diagram for police body camerasA causal diagram for police body cameras. An officer's attitude affects whether the officer volunteers to wear a camera and also the number of complaints against them. The camera may also affect complaints directly.officer attitudewears cameracomplaintsvolunteerseffect we want
If officers choose whether to wear cameras, attitude confounds the comparison.

The comparison mixes the camera's effect with the difference between the kinds of officer who volunteer and those who don't.

  1. Randomize. For example, randomly assign shifts (or officers) to camera or no camera, so the camera's presence can't be connected to anyone's attitude. This is what researchers did in Rialto, California in 2012, randomly assigning shifts. Later, much larger randomized trials found much smaller effects, notably one in Washington, DC with over two thousand officers. Small studies can give dramatic results that don't replicate, a theme we return to in Chapter 9.

History: From Scurvy to Streptomycin

In 1747 the Scottish naval surgeon James Lind took twelve sailors suffering from scurvy aboard HMS Salisbury and divided them into six pairs, giving each pair a different remedy: cider, vinegar, sea water, oranges and lemons, and others. The pair given citrus fruit recovered dramatically. It's often called one of the first controlled trials, though with two patients per group it was a tiny one.

Randomization came much later. Ronald Fisher argued for it in agricultural experiments in the 1920s and 1930s, randomly assigning fertilizers to plots of land. In 1948 the British Medical Research Council published a trial, designed by the statistician Austin Bradford Hill, in which tuberculosis patients were randomly allocated to the new antibiotic streptomycin plus bed rest, or to bed rest alone. It is often called the first modern randomized controlled trial. Today almost no new drug is approved without one.

Interlude (Optional): Randomized Trials: The Gold Standard and Its Limits

Randomized controlled trials are called the gold standard because they answer causal questions without needing to know, or even guess, the confounders. But they have limits.

  • Ethics. We can't randomly assign people to smoke, or to live near a polluting factory, or to be arrested. Many of the most important questions in toxicology and criminal justice can only be studied observationally.
  • Who takes part. Trial volunteers are often healthier or more motivated than the patients who will later use the treatment, so results may not carry over.
  • Compliance. People assigned to a treatment may not take it.

So scientists also look for natural experiments, where chance or an arbitrary rule assigns the "treatment" for them: a lottery for school places, a policy that starts on a particular date, a birthday that falls just before or after a cut-off. A whole field, causal inference, is devoted to drawing causal conclusions from data that weren't randomized, using diagrams like the ones in this section. The Book of Why by Pearl and Mackenzie is a readable introduction.

Check Yourself

A study of 10,000 adults finds that people who drink coffee daily have lower rates of liver disease.

What kind of study is this?
Which of these is a confounder of coffee and liver disease?

Key Takeaways

  • An association between X and Y can come from X causing Y, or from a confounder causing both.
  • A causal DAG draws what influences what. A confounder is a common cause of exposure and outcome.
  • In an observational study units choose their own exposure; in an experiment the researcher assigns it.
  • Randomization makes the treatment independent of every pre-existing characteristic, so it removes confounding, even by things nobody measured.

1.6 Independence and IID data

Almost every method in this course assumes that each observation brings new information. If you measure the refractive index of the same glass fragment five times, you learn a lot about that fragment and the measuring instrument, but very little about glass in general. Five fragments from five different windows tell you far more.

Here is the idea in everyday language; Chapter 3 makes it precise with probability.

Definition: Independence and IID (Informal)

  • Observations are independent if learning the values of some of them doesn't change what we expect from the others.
  • They are identically distributed if each one is produced by the same mechanism.
  • Observations that are both are called IID ("independent and identically distributed"). A simple random sample from a large population gives (approximately) IID observations, and the word random sample in later chapters will mean exactly this.

Independence is surprisingly hard to fake. People asked to write down "random" coin flips almost always switch between H and T too often, because a run of five heads feels non-random. Independent flips don't remember what came before, so they produce longer runs than our intuition expects. Try it.

Can you fake a coin?

Without flipping anything, invent a "random" sequence of 50 coin flips by pressing the H and T buttons (or the H and T keys while a button is focused). Then compare your sequence with 5,000 sequences from a genuinely fair, independent coin. Two features give fakers away: how often the sequence switches between H and T, and the longest run of the same face.

TopTop: your sequence as a row of squares. Bottom left: histogram of the number of switches in 5,000 random sequences, with your value marked. Bottom right: histogram of the longest run, with your value marked.

This isn't just a party trick. Auditors and forensic accountants use the same idea to spot invented numbers in expense reports and fabricated data in scientific papers: made-up data are usually too regular.

Why are long runs so common? Each flip has a 1 in 2 chance of matching the one before it, so once a flip has landed, the chance that the next four all match it (making a run of five) is 12×12×12×12=116. That is unlikely at any one place, but in 50 flips there are 46 places where a run of five could start. Simulation shows that about 4 out of every 5 sequences of 50 fair flips contain a run of five or more identical faces. Your intuition judges each run on its own ("five in a row, how unlikely!") instead of counting all the places one could have happened. We will be able to compute these chances properly in Chapter 3.

Example 1.13: Independent or Not? ★ lecture example

For each dataset, decide whether it is reasonable to treat the observations as IID. If not, explain what connects them.

  1. The refractive index of one glass fragment, measured five times.
  2. Daily ozone levels in New York City from May to September 1973 (R's airquality).
  3. Twenty pills chosen at random from a seizure of 5,000 pills.
  4. The test scores of the 30 students in one classroom, used to describe all students in the city.
  1. Not IID for learning about glass in general: all five share the same fragment. They are reasonable as repeated readings for learning about the instrument's measurement error on that fragment. What counts as independent depends on the question.

  2. Not independent. Weather comes in spells: a hot, still day tends to be followed by another. We can check by comparing each day's ozone with the next day's:

R
airquality$date <- as.Date(paste(1973, airquality$Month,
                                 airquality$Day, sep = "-"))
ggplot(airquality, aes(x = date, y = Ozone)) +
  geom_line() + geom_point(size = 1, na.rm = TRUE) +
  labs(x = NULL, y = "ozone (ppb)")
Line plot of daily ozone in New York City from May to September 1973, in parts per billionLine plot of daily ozone in New York City from May to September 1973, in parts per billion. The series rises and falls in runs of several days, with highs above 100 mostly in July and August (and one in late May), and most of the lows below 20 in May and September. There are gaps where values are missing. 0 50 100 150 May Jun Jul Aug Sep Oct ozone (ppb)
R
oz <- airquality$Ozone
today    <- oz[-length(oz)]   # days 1 to 152
tomorrow <- oz[-1]            # days 2 to 153
cor(today, tomorrow, use = "complete.obs")
output
[1] 0.5515109

The two vectors are lined up so that the ith entry of today and the ith entry of tomorrow are consecutive days. Plotting one against the other shows the connection directly:

R
ggplot(data.frame(today, tomorrow), aes(x = today, y = tomorrow)) +
  geom_point(alpha = 0.7, na.rm = TRUE) +
  labs(x = "ozone today (ppb)", y = "ozone tomorrow (ppb)")
Scatterplot of ozone on one day (horizontal axis) against ozone on the next day (vertical…Scatterplot of ozone on one day (horizontal axis) against ozone on the next day (vertical axis) in New York, 1973. The points drift upwards from lower left to upper right: low-ozone days tend to be followed by low-ozone days, and high by high, with a lot of scatter. 0 50 100 150 0 50 100 150 ozone today (ppb) ozone tomorrow (ppb)

If days were independent, knowing today's ozone would tell you nothing about tomorrow's, and the cloud of points would have no tilt. Instead it tilts upwards: high days cluster together, and the correlation between consecutive days is about 0.55 (Chapter 6 explains this scale; 0 would mean no connection). Data collected over time are rarely independent, and methods that assume independence will be overconfident.

  1. Approximately IID. Random selection from a large batch makes each pill a fresh draw from the same mechanism. (Strictly, sampling without replacement creates a tiny dependence: if the first pill is fake, there's one fewer fake left. With 20 out of 5,000 it is negligible. Chapter 4 handles the case where it isn't.)

  2. Not IID for that purpose. Students in the same classroom share a teacher, a school and often a neighbourhood, so their scores are connected (a cluster), and one classroom doesn't represent the city. Thirty students from one class carry far less information than thirty students chosen at random from across the city.

Check Yourself

A lab runs a drug test on 50 urine samples. Twenty-five were collected from one person over 25 days; the other 25 come from 25 different people.

Which set of 25 tells you more about the rate of positive tests in the population?

Think About It: When Is the Same Thing Measured Twice?

A study of a new reading program measures 400 children: 20 children in each of 20 classrooms. A second study measures 400 children, each from a different school. Both report "n = 400". Which do you think gives the more reliable answer about the program, and why might a report that just says "n = 400" mislead you?

The second. Children in the same classroom share a teacher, a timetable and classmates, so their results move together: if the teacher is excellent, all 20 do well. The first study behaves more like a study of 20 classrooms than of 400 independent children. "n = 400" counts measurements, not independent pieces of information. Always ask how the observations are connected before trusting a sample size.

Key Takeaways

  • Independent observations don't inform each other; identically distributed observations come from the same mechanism; together they are IID.
  • Repeated measurements of one unit, data over time, and clusters are usually not independent.
  • Independence produces more streaks than people expect; invented data are usually too regular.

1.7 The map of the course

We can now see the whole course in one picture. There is a population, or more generally a data-generating process, that we want to understand. We observe a sample of data from it.

The map of the courseThe map of the course. On the left, a box labelled population and data-generating process. On the right, a box labelled sample and data. An arrow from left to right is labelled probability, chapters 3 to 7: if we knew the mechanism, what data would it produce? An arrow from right to left is labelled inference, chapters 8 and 9: given the data, what can we say about the mechanism? A loop on the data box is labelled describe, chapter 2. An arrow from the data box down to a box labelled a new case is labelled predict.population /mechanismsample /dataa new caseprobability (Ch 3–7)inference (Ch 8–9)predictdescribe (Ch 2)
Probability reasons forwards from the mechanism to the data. Inference reasons backwards.

Backwards reasoning is only possible because we first understand forwards reasoning. To judge whether 38 cocaine-positive bags out of 40 is consistent with "at least 90% of all 2,000 bags are cocaine", we need to know what samples from such a population typically look like. That is why the course spends five chapters on probability before it returns to data.

Interlude (Optional): The Two Cultures

In 2001 the statistician Leo Breiman published a famous essay, Statistical Modeling: The Two Cultures. He described two communities working with data.

  • The data-modelling culture (traditional statistics) writes down a model of the mechanism, with interpretable parameters, and uses data to learn those parameters. Its goal is inference: understanding.
  • The algorithmic culture (machine learning) treats the mechanism as a black box and searches for whatever function predicts best on new data. Its goal is prediction.

Breiman, who worked in both, argued that statisticians had been too slow to adopt the second culture. He was right: neural networks, recommendation engines and language models are triumphs of prediction. But the story has a sequel. In 2008 Google launched Google Flu Trends, which predicted flu levels from what people typed into its search engine, faster than official surveillance. It tracked ordinary flu seasons well at first, though it missed the 2009 swine-flu pandemic. Then in the 2012–13 season it predicted more than twice as many flu-related doctor visits as actually happened. The search patterns had changed (media coverage, changes to the search engine itself), and a model with no understanding of the mechanism couldn't notice. Lazer and colleagues described the failure in Science in 2014: "The Parable of Google Flu: Traps in Big Data Analysis".

The lesson isn't that one culture wins. Prediction without understanding breaks when the world changes (remember the chicken). Understanding without good prediction is hard to test. Modern statistics and machine learning use both, and this course gives you the foundations of each.

Think About It: Which Way Are You Reasoning?

For each statement, decide whether it reasons forwards (probability: from mechanism to data) or backwards (inference: from data to mechanism). (a) "If this coin is fair, 10 heads in a row would happen about once in a thousand tries." (b) "We got 10 heads in a row, so this coin is probably not fair." (c) "If the vaccine had no effect, a difference as large as 28 versus 71 per 100,000 would almost never happen by chance." Notice how (c) uses a forwards calculation to reach a backwards conclusion. That move is the whole idea of Chapter 9.

(a) forwards: it assumes the mechanism (a fair coin) and describes the data it would produce. (b) backwards: it starts from the data and concludes something about the mechanism. (c) a forwards calculation ("if no effect, then...") used to judge a backwards question (does the vaccine work?). Hypothesis tests in Chapter 9 have exactly this shape.

Key Takeaways

  • Probability goes from mechanism to data; inference goes from data back to mechanism; prediction goes from data to the next case.
  • We learn probability first because we can't judge data without knowing what chance alone can produce.

1.8 Exercises

Each exercise has a hint and an answer button. Try the exercise first; open the hint if you are stuck; and only look at the answer to check your own. The answers are brief: in a homework or exam you would be expected to explain your reasoning in full sentences.

Exercises

  1. Costs change predictions. A hospital must decide how many units of type O-negative blood to keep in stock each week. Describe the two kinds of mistake it can make and what each costs. Would you expect the best stock level to be above or below the average weekly demand? Why?

    One mistake is having too little blood, the other too much. Donated red blood cells can only be stored for about six weeks. Which mistake can cost a life? Recall from Section 1.1 what a lopsided loss does to the best decision.

    Too little: a patient who needs O-negative (the universal donor type, used in emergencies) can't get it, which can be fatal or require costly emergency transport. Too much: units expire unused, wasting a scarce donation and money. A shortage is far worse than waste, so the loss is lopsided and the best stock level is above the average weekly demand, with a safety margin.

  2. Which kind of question? Classify each as descriptive, predictive, inferential or causal, and explain. (a) Does a new training program reduce the error rate of fingerprint examiners? (b) What fraction of the 2,000 bags in a seizure contain fentanyl? (c) What was the average blood alcohol level of the drivers stopped at a checkpoint last night? (d) Which of tomorrow's flights is most likely to be delayed?

    Use the clue words in Example 1.5. For (b), ask yourself whether all 2,000 bags would realistically be tested.

    (a) Causal: "reduce" asks about the effect of an intervention. (b) Inferential if, as usual, only a sample of bags is tested and the result is extended to all 2,000 (it would be descriptive if every bag were tested). (c) Descriptive: a summary of the drivers actually stopped. (d) Predictive: a guess about unseen future outcomes.

  3. Population and sample. A university wants to know how many hours per week its students work at paid jobs. It emails a survey to all 15,000 students; 1,100 reply. Identify the population, sample, parameter and statistic. Give two reasons the result might be biased, and say in which direction each would push the estimate.

    Who chose to be in the sample? Think about whether students who work many hours have more time, or less time, to answer surveys, and whether they might find the topic more interesting.

    Population: all 15,000 students. Sample: the 1,100 who replied. Parameter: the average weekly hours worked by all 15,000. Statistic: the average among the 1,100. Possible biases: (i) students with heavy work schedules have less free time to answer, which pushes the estimate down; (ii) students who work may find the topic relevant and be keener to reply, which pushes it up. Also, people may misremember or round their hours. Emailing everyone doesn't make it a random sample: the students chose themselves. (Other well-argued reasons are fine.)

  4. Sampling in R. Using USArrests, (a) compute the population mean of the Assault variable; (b) use set.seed(1) and sample() to take a simple random sample of 8 states and compute the sample mean; (c) use replicate() to take 2,000 samples of size 8 and compute the average and standard deviation of the 2,000 sample means. Comment on what you find.

    Adapt the code of Example 1.6, replacing Murder by Assault and 10 by 8. Then compare the average of the 2,000 sample means with your answer to (a).

    (a) mean(USArrests$Assault) gives 170.76 assault arrests per 100,000. (b) With set.seed(1) and mean(sample(USArrests$Assault, 8)) you get 160 (the exact value depends on how you sample, but should be in the range 120 to 220). (c) The 2,000 sample means average about 170, close to 170.76, and their standard deviation is about 26.5. Random samples are right on average, but a single sample of 8 typically misses by about 26.

  5. Glass again. In the fgl data, compare the average magnesium (Mg) content of the six glass types with aggregate(). (R's help page for fgl calls Mg manganese, but it is magnesium.) Suggest a rule using magnesium that separates window glass (WinF, WinNF, Veh) from the other types, and use table() to count how often your rule is wrong.

    aggregate(Mg ~ type, data = fgl, FUN = mean). The three window types average around 3, the others around 1. Try a cut-off in between, and build the table with table(fgl$Mg > 2.5, fgl$type %in% c("WinF", "WinNF", "Veh")).

    Averages: WinF 3.55, WinNF 3.00, Veh 3.54, Con 0.77, Tabl 1.31, Head 0.54. With the rule "window if Mg > 2.5", the rule misses 13 of the 163 window fragments and wrongly calls 4 of the 51 others window glass: 17 mistakes out of 214 (about 92% correct). A cut-off of 2 gives 20 mistakes (11 misses, 9 false alarms). Any sensible cut-off between 2 and 3 is fine, provided you count its mistakes correctly.

  6. Variable types. For each variable in the airquality data (Ozone, Solar.R, Wind, Temp, Month, Day), say whether it is categorical or numerical, and if numerical, discrete or continuous. Which one might sensibly be treated as either, depending on the question?

    Run ?airquality to see what each column measures. Remember Example 1.9: how a variable is recorded (here, often in whole numbers) can differ from what it is.

    Ozone, Solar.R, Wind and Temp are numerical, continuous measurements (some recorded as whole numbers, but the underlying quantities vary continuously). Day is numerical, discrete (day of the month). Month can be treated either way: as categorical, ordinal (May, June, ... as labels, for example when comparing months side by side) or as numerical (for a trend over time). Day could also be argued as a label, since "day 15" in May and in June are not related.

  7. Draw the DAG. Researchers notice that neighbourhoods with more street lights have fewer reported burglaries. (a) Draw a DAG with at least one plausible confounder. (b) Describe a randomized experiment that could test whether street lights reduce burglary, and one practical or ethical difficulty with it.

    What kind of neighbourhood gets more street lights from the city? Could the same thing affect burglary rates directly? For (b), what would you randomize: houses, streets, or whole neighbourhoods?

    (a) For example, neighbourhood wealth → street lights and wealth → burglaries (wealthier areas get more city investment and also have alarms, private security, fewer empty buildings), plus the arrow of interest street lights → burglaries. Population density or how much residents report crime are other reasonable confounders. (b) Randomly choose which of a set of comparable streets or housing estates receive new lighting, then compare burglary over the following year. Difficulties include: crime may simply move to the unlit streets nearby (so the comparison exaggerates the effect); residents can't be blinded; and it may seem unfair to withhold lighting from areas that want it. New York City ran a study like this in public housing developments starting in 2016, randomly assigning temporary floodlights.

  8. Read the trial. In the Salk trial (Example 1.11), suppose the doctors diagnosing polio had known which children were vaccinated. Explain how this could bias the results, and in which direction. (Polio diagnoses in mild cases required judgement.)

    In borderline cases, a doctor's expectations can tip the decision. Which children would a doctor who believed in the vaccine be more ready to diagnose with polio?

    A doctor who expected the vaccine to work might be more willing to diagnose borderline cases as polio in placebo children and to dismiss similar symptoms in vaccinated children. That would push the placebo rate up and the vaccine rate down, making the vaccine look more effective than it really was. (A doctor sceptical of the vaccine could bias it the other way.) Blinding the diagnosing doctors removes this route.

  9. Faking data. Use the coin-faking widget in Section 1.6: write your own sequence of 50 flips, then generate a real random one. Record the number of switches and the longest run for each. Repeat with a classmate. In two or three sentences, explain what this suggests about how to spot invented data.

    In 50 genuine flips there are 49 chances to switch, and each happens with probability 1/2. How many switches would you expect? Compare with what you wrote.

    Genuine sequences average about 49×12≈24.5 switches, and the longest run is usually 5 or more. Most people's invented sequences have noticeably more switches (often 30 or more) and longest runs of only 3 or 4. So invented data tend to be too balanced and too regular: checking for the patterns that real randomness produces, such as long runs, can reveal fabrication.

  10. Independence. A website measures its page-load time every minute for a week. Explain why these 10,080 measurements are probably not independent, and why that might make the website's engineers overconfident about the average load time.

    Think about what makes a page slow: busy periods, a server problem, a network outage. Do these last one minute, or longer? What does that mean for the information in minute 2 if you already know minute 1?

    Slowdowns come in spells (a traffic surge at lunchtime, a server running low on memory for an hour), so consecutive minutes are similar, like the ozone days in Example 1.13. The 10,080 measurements therefore carry much less independent information than 10,080 separate visits would. Methods that assume independence (such as the margins of error in Chapter 8) would treat the sample as larger than it effectively is, and so give a margin of error that is too small.