Continuous manuscript · Forty-five chapters

Introduction to Statistics

All four units in reading order. A free, first-pass undergraduate textbook you can read continuously, annotate, or print for personal study.

View weekly syllabus →
Editorial status: This is the complete first-pass manuscript, not an independently peer-reviewed, published textbook. Some mathematical explanations, problem solutions, and source statements still require editorial verification. Interactive laboratories and actual R computation run on their separate web pages; printing the book cannot reproduce those interactions.

Mathematics Project · James Howard

Introduction to Statistics

Questions, evidence, probability, inference, and statistical reasoning

Expanded textbook draft · November 2026

Independent educational material; no tuition, accreditation, academic credit, or required account.

Unit 1

Thinking with and describing data

Lesson 01 · Week 1

Why Statistics?

Learning to reason with evidence when the whole story is unavailable.

Learning objectives:

  • Distinguish a population from a sample.
  • Explain the difference between description and inference.
  • Identify uncertainty rather than treating an estimate as a fact.

Imagine you want to know how much time students at a university spend studying each week. There is a perfectly straightforward way to find out: ask every single student, verify every answer, and calculate the result.

There are two problems. First, this would be expensive. Second, the answers might not be entirely accurate. What counts as studying? Does watching a lecture count? What about having the textbook open while watching television?

Welcome to statistics. The mathematics is often the easy part.

We rarely see the whole picture

The population is the complete group about which we want to know something. If our question concerns all students currently enrolled at a particular university, they constitute the population.

A sample is the subset we actually observe. We might survey 200 students and estimate something about the university’s 20,000 students.

A number summarizing the population—such as its true average study time—is a parameter. A number calculated from our sample is a statistic. Parameters are generally unknown. Statistics are what we have in our hands.

A statistic can be useful without being an exact representation of the parameter. The question is how much uncertainty accompanies it.

Two different jobs

Descriptive statistics summarize observed information. A histogram of the 200 students’ reported study hours describes that sample. So do its mean and median.

Inferential statistics use observed data to make claims beyond the observations. If we use the 200 students to estimate the average for all 20,000, we are doing inference.

That second job is harder than it looks. Which students were asked? Did they volunteer? Did everyone respond? Could the questionnaire have nudged respondents toward particular answers?

A beautifully precise average from a hopelessly biased sample is still a hopelessly biased answer.

Variation is not an inconvenience

Suppose the five students we asked report 2, 4, 6, 8, and 10 hours. Their mean is 6 hours. That does not mean anyone must study exactly 6 hours, or that the next student will.

Statistics begins by accepting that observations vary. Rather than pretending variation does not exist, we describe it and ask whether our results are stable in the presence of it.

This becomes especially important when comparing groups. A difference of two points on a test could be meaningful, irrelevant, or entirely unsurprising given the variability in scores. The difference itself cannot tell us which.

What this course will do

We will start by learning how to describe data. Then we will study randomness and sampling. Eventually we will build toward confidence intervals, hypothesis tests, regression models, and the rather remarkable problem of distinguishing patterns from coincidence.

The goal is not to memorize a table of formulas. The goal is to know which question each formula answers, what assumptions it requires, and where it can lead us astray.

Check your understanding

  1. A city surveys 400 residents about transit. Identify the population, the sample, a possible parameter, and a possible statistic.
  2. A news report says, “The survey found that 61% support the proposal.” Does that number necessarily describe the population?
  3. Give one way that a large sample could still produce a misleading estimate.
Suggested responses
  1. Population: the city’s residents (if that is the target). Sample: the 400 surveyed. Parameter: the true citywide support rate. Statistic: the observed support rate among 400 respondents.

  2. No. It describes the respondents; generalizing requires information about how they were selected and how uncertainty was assessed.

  3. The sample might systematically exclude residents without internet access, or respondents might self-select.

A design problem, before any formulas

Here is a challenge you will return to in the Week 1 investigation. A university wants to know whether a statistics-preparation workshop causes students to perform better. Someone surveys the students who attended, compares their marks with those who did not, and claims that the difference is the benefit of attending.

What did the researcher actually learn?

For the people measured, the researcher may have described an association between attendance and scores. But students who attend voluntarily may differ from those who decline in prior knowledge, time, motivation, or access. We do not know what their scores would have been without attending. And even a carefully randomized experiment involving willing volunteers would not necessarily represent all university students.

These are three separate limitations:

  • Description: do we correctly summarize the observations we collected?
  • Causal inference: is the observed difference a credible estimate of the effect of an intervention?
  • Generalization: which population could this result describe?

The point of the first week is not to learn a formula for each problem. It is to stop one kind of claim from quietly turning into another. Go to the interactive study-design workshop and predict what happens when participation and treatment selection change.

Specify the claim before collecting its denominator

A research question should identify the target population, measurement, time window, and quantity to estimate. “Do students study enough?” is underspecified. “What fraction of currently enrolled undergraduates report at least ten hours of independent study during the previous seven days?” names a measurable proportion, although the quality of self-report still needs investigation.

Suppose a university has 20,000 undergraduates and selects 200 by simple random sampling. Of 160 respondents, 96 report at least ten hours. The observed respondent proportion is 96/160=0.6096/160=0.60. It is not 96/200=0.4896/200=0.48 unless nonresponse has explicitly been coded as nonsupport for a justified target, which would answer a different question. The response rate is 160/200=0.80160/200=0.80. Distinguish the denominator selected, the denominator responding, and the population to which an estimate is intended to apply.

An inferential report connects question, design, evidence, estimate, uncertainty, and limitations. Each link can fail independently. More elaborate computation cannot repair an undefined outcome, a missing population, or a self-selected comparison silently described as random assignment.

Further investigation

  1. Write a fully specified question about travel time to campus, including its population and time window.
  2. In the example above, how many selected students did not respond, and what is the response rate?
  3. Give one limitation that would remain even if every selected student responded.
Worked further responses
  1. One defensible example is the mean door-to-door travel time of undergraduates attending in-person classes during a specified teaching week. Define how multiple journeys are combined and whether nontravellers are in the target.
  2. Forty did not respond; the response rate is 80%.
  3. Misremembered study hours, ambiguous wording, frame omissions, or the original sampling design could still limit interpretation. Complete response addresses one mechanism, not every error source.

Open chapter with navigation, interactive labs, and R examples →

Lesson 02 · Week 1

Data, Variables, and Measurement

The numbers mean nothing until we decide what they represent.

Learning objectives:

  • Distinguish categorical and quantitative variables.
  • Recognize different measurement scales and their limitations.
  • Explain why collection methods matter as much as calculations.

We are going to do something statisticians are surprisingly prone to neglect: ask what the numbers mean before doing mathematics with them.

Suppose a hospital records a patient’s temperature as 39. Is the patient feverish? We cannot answer without knowing whether that number means degrees Celsius or Fahrenheit. And that is a relatively simple measurement problem.

A dataset is a collection of observations about units: people, events, places, machines, or anything else we can observe. A variable is an attribute measured for each unit. One person can contribute multiple variables, such as age, reported study hours, and preferred transportation.

Names are not numbers

A categorical variable puts observations into groups. A student’s major or preferred musical genre is categorical. We can count categories and calculate their proportions. Averaging majors, however, makes no sense.

A quantitative variable records numerical amounts or counts. Distance traveled, number of books read, and exam scores are quantitative.

Quantitative variables are often described as discrete (counts such as number of siblings) or continuous (measurements such as temperature, which can in principle take values across an interval). The distinction depends partly on the measurement process: a thermometer might report tenths of a degree even though temperature itself varies continuously.

Measurement scales constrain conclusions

Four names are often useful:

  • Nominal: categories without an inherent ordering, such as blood type.
  • Ordinal: ordered categories, such as poor, fair, good, and excellent.
  • Interval: numerical differences are meaningful, but zero is not an absence of the quantity, such as temperature in Celsius.
  • Ratio: differences and ratios are meaningful and zero represents an absence, such as mass.

If a respondent gives a service a rating of 4 rather than 2, we can say the rating is higher. We cannot automatically conclude the respondent liked it twice as much. The numbers might label an ordinal scale rather than measure a ratio.

Where did these data come from?

Suppose a school’s website asks visitors whether students should have longer holidays. Ten thousand people respond. That is a lot of observations, but it is not necessarily a useful estimate of what the school’s students think.

The visitors were not randomly selected from the students. They might not even be students.

This is called selection bias: the mechanism that puts people in our dataset is related to what we want to measure.

Other problems include missing responses, ambiguous questions, miscalibrated instruments, and variables that are convenient to collect but poorly represent the underlying concept.

An easy mistake: treating codes as quantities

Consider the table:

Student Major code Study hours
A 1 5
B 3 8
C 2 4

The mean study time is 17/3≈5.6717/3 \approx 5.67 hours. The mean major code, 2, is arithmetically calculable but conceptually meaningless. Those codes are labels.

A valid operation on numbers is not necessarily a valid operation on data.

Check your understanding

  1. Is a ZIP code categorical or quantitative, even though it contains digits?
  2. What additional information would you need to interpret a recorded temperature of 39?
  3. Why might a voluntary online poll of 100,000 people be less informative than a carefully selected survey of 1,000?
Suggested responses
  1. Categorical: the digits identify a location rather than measuring a quantity. 2. At minimum, the temperature scale and what was measured. 3. Sample selection matters; very large nonrepresentative samples can preserve systematic bias.

Turning a question into a defensible measurement

Suppose we ask whether tutoring improves statistics performance. Before surveying anyone, we have to choose what that means. Is it a final exam score, an independently marked common assessment, a course grade, passing the module, or confidence answering questions? Those are related but different constructs. Asking students how much they feel they learned does not directly measure their demonstrated proficiency.

Write a miniature data dictionary before collecting data:

Variable Meaning Type Measurement problem
Workshop offered Randomized offer of workshop access Binary category Did everyone receive the assigned offer?
Workshop attended Actual participation Binary category Partial attendance may be lost
Prior preparation Pre-workshop knowledge assessment Quantitative score Was the assessment consistent and appropriate?
Later performance Result on the agreed outcome measure Quantitative score Was grading comparable or blinded?
Missing outcome Whether the result was actually observed Binary category Does absence depend on the outcome?

Notice that offered and attended are different variables. If someone receives an invitation but does not attend, including them according to their randomized offer answers a different question from analyzing only people who chose to participate.

The data dictionary is not administrative decoration. It determines whether the analysis can answer the question. You will use these definitions in the Week 1 study-design studio.

The unit of observation controls the denominator

Imagine a clinic file with one row per visit. A person attending five times supplies five rows. The mean waiting time across visits targets a visit-level average; the mean of each person’s average targets a person-level quantity. If frequent visitors have different waits, the two summaries can differ even when every row is accurate. Define whether the unit is a person, visit, household, or measurement before computing a sample size.

Derived variables need operational definitions. Body mass index uses mass in kilograms divided by squared height in metres. Supplying height in centimetres without converting changes the numerical result by a factor of 10,000. A data dictionary should record units, coding, valid ranges, timing, missing-value codes, and transformations. Plausibility checks require subject-matter limits, not just a column’s software type.

Ordinal codes preserve order but not necessarily equal spacing. A shift from category 1 to 2 on a satisfaction scale need not equal a shift from 4 to 5. Means of such codes can be used under an explicitly defended measurement model, but the numeric labels alone do not establish that model. Report category distributions when the spacing assumption is uncertain.

Further practice

  1. A file has 500 visits from 120 people. Which number is the count of independent people?
  2. Is a postal code a quantitative variable because software stores it as an integer?
  3. Specify a data-dictionary entry for travel time that makes its units and missingness unambiguous.
Worked further responses
  1. There are 120 distinct people; whether they are independent still depends on recruitment and relationships. The 500 rows are visits, not 500 independent people.
  2. No. It is a category identifier; arithmetic differences generally lack a measured-distance meaning.
  3. For example: elapsed door-to-door minutes, measured on a designated day, nonnegative numeric values, missing represented as an explicit missing value, with zero reserved for a genuine zero-duration journey if that is allowed.

Open chapter with navigation, interactive labs, and R examples →

Lesson 03 · Week 1

What Sort of Study Are We Actually Doing?

Surveys, observational comparisons, random assignment, blinding, and ethically useful designs.

Learning objectives:

  • Separate observational and experimental study designs.
  • Describe random assignment, control conditions, and blinding.
  • Recognize limitations of causal and population generalization.

Someone discovers that people who drink tea tend to live longer. Should we issue everyone a kettle? Maybe. But the observation itself does not tell us whether tea made anyone live longer.

Before touching a statistical test, we need to understand how the data came into existence.

Observing is not intervening

In an observational study, researchers record exposures, characteristics, and outcomes without assigning the exposure of interest. A survey of commuting habits is observational. So is a study comparing medical outcomes among patients who independently chose different treatments.

A randomized experiment uses a chance mechanism to assign an intervention, such as treatment A or treatment B. Under a suitable design, randomization prevents investigators and participants from systematically choosing treatment groups based on pre-treatment characteristics.

Random assignment does not mean that two realized groups will have precisely the same age, income, or health. Chance still produces imbalances. Rather, those imbalances arise from a known mechanism we can use in inference.

Random sampling is a different machine

Imagine recruiting 100 volunteers and randomly assigning 50 to each intervention. The experiment may support causal inference about the volunteer population under its assumptions, but it does not automatically represent everyone in a city.

Random sampling concerns who enters the study and the population to which we can generalize. Random assignment concerns why groups differ on treatment. They serve distinct purposes.

Controls, blinding, and ethics

A control group supplies a meaningful comparator: usual practice, placebo, or another intervention. A placebo may help distinguish treatment effects from expectations, but it is not ethically acceptable to deny established effective care merely to make a cleaner experiment.

Blinding can reduce measurement or behavior changes related to knowledge of treatment assignments. When blinding is impossible, clearly measured endpoints, pre-registered outcomes, and independent assessment can still improve the study.

In medical and social research, informed consent, safety monitoring, privacy, and ethical oversight are parts of the design—not paperwork to bolt on after the results are interesting.

A small example

A school compares 20 students who enrolled in an optional tutoring program with 20 who did not. The tutoring group gains four more points on average. Maybe tutoring helped. Maybe students seeking tutoring were more motivated or had different prior preparation. A difference between means does not resolve this.

If the school randomly offered access to tutoring, that can improve causal identification of the offer’s effect. It may not identify the effect of actually attending tutoring when attendance differs from the assignment.

Check yourself

  1. A random telephone survey asks about voting intentions. Is treatment randomly assigned?
  2. A randomized trial recruits only university students. What population-generalization concern remains?
  3. Why might measuring outcomes without knowing treatment assignment improve an experiment?
Worked responses
  1. No. Random selection for observation and treatment assignment are different operations.

  2. University student volunteers may not represent the broader population.

  3. Blinding can reduce biased outcome measurement or interpretation linked to treatment knowledge.

Further reading

See the experimental-design chapter of OpenStax Introductory Statistics 2e.

A model in which sampling and assignment can be separated

Consider a hypothetical university of 1,000 students. Half enter with more prior preparation, and half have less. Suppose a workshop would help both groups, but its benefit is larger for those with less preparation.

Imagine that 90% of the more-prepared students volunteer for a study but only 20% of the less-prepared students do. The volunteers are not a miniature copy of the university. Because effects differ between groups, the average treatment benefit among volunteers need not equal the benefit in the university population.

Now suppose the researchers randomize workshop access among those volunteers. This improves our ability to learn an effect among the selected participants. It does not turn the volunteers into a representative sample.

Finally, imagine that researchers instead allow students to choose whether to attend. More-prepared students may select into treatment at a different rate. The raw difference between those who attended and those who did not can combine a real treatment effect with differences in prior preparation.

These are distinct mechanisms. Random sampling addresses who we can generalize to. Random assignment addresses a causal comparison. Neither automatically supplies the other.

Work through each mechanism in the interactive study-design studio. The model reports expected counts rather than actual experimental data, so a perfectly balanced expectation is not a promise of perfectly balanced real treatment groups.

Assignment, receipt, and analysis population

Random assignment specifies the offered intervention, but participants may not receive or adhere to it. An intention-to-treat comparison follows assigned groups and estimates the effect of the assignment strategy under its design. Comparing only those who complied can reintroduce selection: people who adhere may differ in prognosis or resources. A treatment-received analysis needs additional assumptions to identify a causal effect.

Suppose 50 volunteers are assigned to each arm of a hypothetical trial. Ten assigned to treatment never attend, and five controls obtain similar services elsewhere. Discarding these 15 people destroys the original randomized comparison unless the missingness or compliance mechanism is addressed. Retaining assignment may dilute the difference relative to perfect adherence, but it preserves a clearly defined policy question about offering the treatment.

Blocking randomizes within groups such as site or baseline severity to improve balance or precision. Blinding reduces some behavior and measurement changes associated with knowledge of assignment. Neither replaces ethical consent or outcome validity. State who was randomized, the allocation unit, the implemented mechanism, and the planned analysis population before interpreting a treatment coefficient.

Further practice

  1. Distinguish an allocation unit from an outcome-measurement unit in a school-randomized study.
  2. Why can analyzing only adherent participants defeat randomization?
  3. Does an observational study become randomized when a computer randomly orders its rows?
Worked further responses
  1. Schools receive assignments; outcomes may be measured on pupils nested within them. The analysis must respect the assignment unit and dependence.
  2. Adherence is a postassignment behavior potentially associated with outcomes. Selecting on it can make analyzed groups systematically different.
  3. No. Row ordering does not change how exposure or treatment was assigned to people.

Open chapter with navigation, interactive labs, and R examples →

Lesson 04 · Week 2

The Spreadsheet Is Not the Study

Units, missing values, duplicates, coding decisions, data dictionaries, and reproducibility.

Learning objectives:

  • Identify common data-integrity problems before analysis.
  • Describe a reproducible cleaning log and data dictionary.
  • Distinguish missing observations from numerical zeros.

The spreadsheet says a patient’s temperature is 101. In Fahrenheit, that suggests a fever. In Celsius, it suggests the patient was briefly inside an industrial process.

The computer will calculate the average either way.

A mathematical operation on a column is not evidence that the column represents a coherent quantity. We have to understand the records first.

Start with the unit of observation

What does one row describe: one person, one appointment, one hospital admission, or one measurement? If a patient has five visits and another patient has one, treating six rows as six independent people changes the scientific question.

A data dictionary records what variables mean, allowed values, units, collection dates, and whether a value is a category, count, or measurement.

Missing does not mean zero

Suppose recorded incomes are 40, 50, 60, and blank. Replacing the blank with zero produces a mean of 37.5. Omitting the blank produces 50. Neither is guaranteed to estimate the intended population mean; the correct treatment depends on why the value is missing.

Unknown is not the same thing as none. Use explicit missing-value markers rather than inventing a number.

Also inspect duplicates, impossible dates, changing codes, mismatched units, and whether identifiers inadvertently reveal personal information.

A reproducible cleaning log

Keep the original source read-only. Record transformations as scripts or documented operations: which rows were excluded, which categories were recoded, which measurement conversions were made, and why.

For example, converting pounds to kilograms is reproducible if the original units and conversion are documented. Deleting “suspicious” high observations without stating the criterion is not.

A tidy-looking result can still be inaccurate if someone has quietly deleted the events that made the dataset interesting.

Example audit in R

R’s airquality example includes historical observations and missing measurements:

data(airquality, package = "datasets")
dim(airquality)
colSums(is.na(airquality))
summary(airquality)

We can inspect missingness before fitting a model. If we use na.omit(), report how many rows were dropped and which variables caused the exclusion. Our air-quality field notebook demonstrates this.

Check yourself

  1. Why does replacing a missing measurement with zero alter the research claim?
  2. An observation appears twice. When should it be removed, and when might it be legitimate?
  3. What metadata would you require before sharing an analysis-ready dataset?
Worked responses
  1. Zero is a measured value with scientific meaning, whereas a missing measurement is unknown.

  2. Remove a confirmed erroneous duplicate; repeated real events or measurements might be legitimate separate records.

  3. Source, units, observation grain, definitions, collection period, transformations, exclusions, licensing, and known limitations.

Further reading

The R documentation for the airquality dataset demonstrates why source details matter.

Demonstrate a transformation without destroying the evidence

Suppose five synthetic records report minutes as [10,12,−99,15,1200][10,12,-99,15,1200], and the documented codebook says −99-99 means missing. The raw mean is 227.6, a valid arithmetic calculation of an invalidly mixed code and measurement. Converting only the documented code to missing leaves observed values [10,12,15,1200][10,12,15,1200] and mean 309.25. That surprising result does not authorize deleting 1200. It requires checking units, provenance, and whether the long duration is genuine.

If source verification establishes that 1200 was recorded in seconds while the other entries were minutes, a documented conversion gives [10,12,15,20][10,12,15,20], mean 14.25. Preserve the raw entry, record the corrected units and reason, and keep the missing record as missing. This sequence illustrates why a cleaning log must distinguish confirmed correction from a guess made to make results look reasonable.

Duplicate detection also needs a key. Two people can share a name and outcome; one person can legitimately have repeated visits. Dropping identical-looking rows without defining record identity can erase valid observations. A reproducible pipeline should assert expected keys and retain counts at every filtering stage.

Further practice

  1. Why is converting every zero to missing unsafe?
  2. Which file should remain unchanged when a verified unit error is corrected?
  3. What should be reported if the origin of the value 1200 cannot be resolved?
Worked further responses
  1. Zero may be a valid measurement, and blanket replacement changes the distribution and denominator.
  2. The immutable raw source. Write a derived dataset and transformation log instead.
  3. State the uncertainty, retain the raw record, and compare results under defensible handling scenarios. Do not silently declare the value erroneous because it is inconvenient.

Open chapter with navigation, interactive labs, and R examples →

Lesson 05 · Week 2

Center and Spread

What an average can tell us—and what it can hide.

Learning objectives:

  • Calculate and interpret the mean and median.
  • Explain the effect of an outlier on different summaries.
  • Distinguish standard deviation from the range.

One of my favorite statistical questions is also one of the least useful without context: What is the average?

Consider five annual incomes, measured in thousands of dollars:

40,45,50,55,60.40,\quad 45,\quad 50,\quad 55,\quad 60.

The arithmetic mean adds the observations and divides by their number:

xˉ=1n∑i=1nxi=40+45+50+55+605=50.\bar{x}=\frac{1}{n}\sum_{i=1}^{n}x_i =\frac{40+45+50+55+60}{5}=50.

The mean is the balancing point of the values. It uses every observation, which is both its strength and its vulnerability.

The median tells another story

The median is the middle value after sorting the observations. Here it is also 50.

But imagine the fifth person wins a tremendous prize. Replace 60 with 600. Our data become:

40,45,50,55,600.40,\quad45,\quad50,\quad55,\quad600.

The mean is now 158. The median remains 50. Neither calculation is wrong, but they answer slightly different questions.

The mean describes a mathematical balance point and is strongly affected by extreme observations. The median describes the middle of the ordered observations and is generally more resistant to outliers.

If there are an even number of observations, the median is conventionally the average of the two middle values.

Spread: how different are the observations?

A center without a description of variation is often misleading.

The simplest measure of spread is the range:

range=max⁡(x)−min⁡(x).\text{range}=\max(x)-\min(x).

A more sophisticated measure is the sample standard deviation, ss:

s=∑i=1n(xi−xˉ)2n−1.s=\sqrt{\frac{\sum_{i=1}^n(x_i-\bar{x})^2}{n-1}}.

The square root returns the answer to the original units. Dividing by n−1n-1, rather than nn, produces the familiar sample variance estimator used to estimate population variance under standard assumptions.

Standard deviation is not the average distance from the mean. It is the square root of the average squared deviation with that sample correction.

Standard deviation, like the mean, can be strongly affected by extreme values. For heavily skewed data, the median and interquartile range may give a more representative description of a typical observation.

Experiment with an outlier

Below, change the final observation. The mean, median, and sample standard deviation will update immediately.

Try setting the final value to 60, then to 600. Ask yourself which summary best represents a typical member of this tiny group, and why.

Check your understanding

  1. For 2,4,6,82,4,6,8, calculate the mean and median.
  2. If the largest observation increases by 100, what happens to the mean of a five-observation dataset?
  3. Can two datasets share the same mean but have dramatically different variability?
Suggested responses
  1. Both are 5. 2. The mean increases by 20. 3. Yes: compare 5, 5, 5 with 0, 5, 10. Both have mean 5, but the latter is more variable.

Why the mean and median solve different problems

For any proposed center cc, expand xi−c=(xi−xˉ)+(xˉ−c)x_i-c=(x_i-\bar x)+(\bar x-c). Summing squared deviations gives

∑i(xi−c)2=∑i(xi−xˉ)2+n(xˉ−c)2,\sum_i(x_i-c)^2=\sum_i(x_i-\bar x)^2+n(\bar x-c)^2,

because centered deviations sum to zero. The mean uniquely minimizes squared error. A median instead minimizes ∑i∣xi−c∣\sum_i|x_i-c|; moving a proposed center across an ordered observation changes how many distances increase and decrease. For an even sample, any point between the two middle values minimizes absolute error; the midpoint is the conventional reported median. Neither center is universally correct without specifying what kind of loss or description matters.

For the original five incomes, squared deviations from 50 are 100,25,0,25,100100,25,0,25,100, summing to 250. The sample variance is 250/4=62.5250/4=62.5 and the standard deviation is 62.5≈7.9057\sqrt{62.5}\approx7.9057 thousand dollars. The variance has squared-income units; the standard deviation returns to income units. For a descriptive population consisting of exactly these five people, dividing by five instead gives population variance 50. The choice of denominator reflects the intended quantity, not a universal preference for one button.

The n−1n-1 sample variance is unbiased for population variance under independent identically distributed finite-variance sampling. Its square root is not generally an unbiased estimator of population standard deviation. That distinction matters when interpreting the word “unbiased.”

Additional practice

  1. Calculate the mean, median, sample variance, and range for [1,2,3,10][1,2,3,10].
  2. Add 100 to every observation. What changes? Multiply every value by −2-2 instead; how does the standard deviation change?
  3. Explain which summary you would report for typical income and which for total income per person.
Worked additional solutions
  1. Mean 4, median 2.5, squared deviations 9+4+1+36=509+4+1+36=50, sample variance 50/350/3, and range 9.
  2. Adding 100 shifts centers but leaves spread unchanged. Multiplying by −2-2 multiplies standard deviation by 2 and variance by 4; it also reverses order.
  3. Median may better describe a middle person’s skewed income. The mean multiplied by population size reproduces the total. Report distributional context rather than asking one statistic to answer both questions.

Open chapter with navigation, interactive labs, and R examples →

Lesson 06 · Week 2

Visualizing Distributions

Bar charts, histograms, skew, and the subtle ways a graph can change the story.

Learning objectives:

  • Choose an appropriate graph for categorical versus quantitative variables.
  • Describe shape, center, spread, and unusual observations.
  • Explain why histogram bin width influences what a distribution appears to show.

A good graph can make a complicated dataset understandable in seconds. A bad graph can make a perfectly ordinary dataset look terrifying.

The numbers don’t get to object. That is our job.

Count categories with a bar chart

Imagine asking 100 commuters how they get to work. Forty say car, 30 bus, 20 train, and 10 bicycle. These are categorical observations. A bar chart is appropriate: each category gets its own bar, and the height represents a count or proportion.

Bars for distinct categories typically have gaps between them. Rearranging unordered categories does not change the underlying data.

For a quantitative variable such as commute time, a categorical bar chart is usually not the right choice. We care about numerical order, distance, and the distribution across intervals.

A histogram is not simply a bar chart with touching bars

A histogram partitions quantitative values into intervals called bins. Each observation falls into one bin. For equal-width bins, we can draw bar heights proportional to counts. For unequal-width bins, the area of each bar, not merely its height, must represent frequency.

The interval boundaries matter. Are scores of exactly 20 placed in the 10–20 bin or the 20–30 bin? A graph should use a consistent convention.

Most importantly, the choice of bin width can change the story a reader sees. Too few bins can hide structure; too many can emphasize random variation.

Describe what you actually see

When reading a distribution, look for four things:

  • Shape: symmetric, right-skewed, left-skewed, single-peaked, or multimodal.
  • Center: where a typical observation seems to fall.
  • Spread: how widely values are dispersed.
  • Unusual observations: gaps, clusters, or apparent outliers that might merit investigation.

Right-skew means a longer tail toward higher values, not necessarily that most observations are high. Income and waiting-time distributions often provide intuitive examples, though specific datasets must be examined rather than assumed to follow a particular shape.

The same data, many pictures

The laboratory uses a synthetic dataset, generated for instruction. Move the number of bins without changing a single observation. Watch which details become prominent. Then examine the frequency table, which includes the numerical counts that the visual representation might obscure.

Check your understanding

  1. Would you usually use a bar chart or histogram for students’ favorite subjects?
  2. Why is it risky to compare raw counts from groups of very different sizes?
  3. Can changing the number of histogram bins change the sample mean?
Suggested responses
  1. Bar chart: favorite subject is categorical. 2. A group with more observations can have a larger count even if a smaller proportion exhibits the property; proportions may be more informative. 3. No. Bin choices change the representation, not the values or the mean.

Unequal bins require density, not raw height

A histogram represents frequencies by rectangle areas. For equal-width bins, counts and heights differ only by a common scale. With unequal widths, raw count heights distort the comparison. A frequency-density height is count divided by bin width; a relative-frequency-density height additionally divides by total count, so all rectangle areas sum to one.

Suppose 20 synthetic waits contain 10 values in [0,5)[0,5) and 10 in [5,15][5,15]. Counts are equal, but the first interval is half as wide. Relative density heights are 10/(20⋅5)=0.1010/(20\cdot5)=0.10 and 10/(20⋅10)=0.0510/(20\cdot10)=0.05 per minute. Both areas are 0.50.5. Equal count heights would imply twice as much area in the second interval and tell the wrong distributional story.

Specify endpoint conventions to prevent double counting. A common scheme uses left-closed, right-open intervals except the final bin includes its right endpoint. Also retain the original observations or an empirical cumulative distribution when possible: a histogram is a lossy summary whose appearance depends on width and origin.

Additional practice

  1. A bin of width 4 contains 8 of 40 observations. Find its relative-frequency-density height.
  2. Can two histograms from the same data have different apparent peaks?
  3. Why should a time plot retain chronological ordering rather than sort observations by value?
Worked additional solutions
  1. 8/(40⋅4)=0.058/(40\cdot4)=0.05 per input unit; the bin area is 0.20.2.
  2. Yes. Changing bins changes aggregation. Compare several defensible widths and inspect the raw or cumulative data before asserting multimodality.
  3. Sorting destroys temporal relationships, potentially hiding trends, seasonality, and dependence.

Open chapter with navigation, interactive labs, and R examples →

Lesson 07 · Week 2

Quantiles, Quartiles, and Outliers

A resistant description of a distribution, with a warning about competing conventions.

Learning objectives:

  • Interpret percentiles and quartiles in an ordered dataset.
  • Calculate an interquartile range and interpret the common 1.5 IQR fence.
  • Recognize that valid quantile algorithms may produce different answers for small samples.

The mean and standard deviation are useful, but they can be dramatically affected by unusual values. Sometimes it is more useful to summarize where the middle of the observations sits.

To do that, we sort the data.

Percentiles and quartiles

The ppth percentile roughly describes the point at or below which pp percent of the data lie. The median is the 50th percentile.

The first quartile, Q1Q_1, is the 25th percentile; the third quartile, Q3Q_3, is the 75th percentile. The interquartile range is

IQR=Q3−Q1.\mathrm{IQR}=Q_3-Q_1.

It describes the spread of the central portion of the data. We commonly report a median and IQR together for distributions that are skewed or contain extreme observations.

There is a subtlety: for a finite sample, software packages use several different rules for determining percentiles. They can disagree, particularly for small datasets. This is not necessarily a software bug. It is a choice of definition.

One explicitly stated convention

For the laboratories on this site, we use a common linear interpolation rule (sometimes called type 7). For nn sorted values x(1)≤⋯≤x(n)x_{(1)} \le \cdots \le x_{(n)}, estimate a quantile at probability pp by interpolating at zero-based position

h=(n−1)p.h=(n-1)p.

If hh falls between two integers, interpolate between the corresponding adjacent observations.

For example, take

2,  4,  6,  8,  10.2,\;4,\;6,\;8,\;10.

For p=.25p=.25, we have h=4(.25)=1h=4(.25)=1, so Q1=4Q_1=4. Similarly, Q3=8Q_3=8, the median is 6, and IQR=4\mathrm{IQR}=4.

This definition is easy to calculate consistently. Other perfectly legitimate textbook conventions may give different quartiles.

Is it an outlier?

A common exploratory rule calls observations outside the inner fences potential outliers:

Q1−1.5 IQR,Q3+1.5 IQR.Q_1-1.5\,\mathrm{IQR},\qquad Q_3+1.5\,\mathrm{IQR}.

For our five observations, the fences are 4−6=−24-6=-2 and 8+6=148+6=14. No value lies beyond them.

Importantly, this is a screening convention, not a scientific definition of an error. A high observation might be completely legitimate. Deleting it automatically can introduce bias and remove the very phenomenon we hope to understand.

A boxplot often shows the median, quartiles, whiskers, and observations outside the chosen fence. Different plotting packages can also use different rules for whiskers.

What not to infer

The interquartile range does not describe every observation. A small IQR does not rule out extreme tails. And quartiles alone cannot tell us whether a distribution has one peak or two.

No single statistic describes everything about a dataset. That is why we use several summaries together.

Check your understanding

  1. For the sorted data 2,4,6,8,102,4,6,8,10, what are the median, IQR, and upper 1.5-IQR fence using this lesson’s rule?
  2. Does an observation beyond the upper fence have to be a measurement error?
  3. Why should we state which method produced the sample quartiles when reporting small datasets?
Suggested responses
  1. Median 6, IQR 4, upper fence 14. 2. No: it is an observation worth investigating, not automatically a mistake. 3. Multiple accepted algorithms can yield different sample percentiles.

Interpolation and boxplot conventions

For sorted [1,2,4,8][1,2,4,8], the type-7 first-quartile position is (4−1)(0.25)=0.75(4-1)(0.25)=0.75 in zero-based indexing. Interpolate 75% of the way from 1 to 2, giving Q1=1.75Q_1=1.75. The third-quartile position is 2.25, yielding Q3=5Q_3=5. Thus IQR is 3.253.25, with fences −3.125-3.125 and 9.8759.875. The maximum 8 is not flagged.

A boxplot’s whiskers commonly end at the most extreme observed values within the fences, rather than at the numerical fences themselves. In this example whiskers end at 1 and 8. R’s boxplot hinges can differ from type-7 quartiles, so an independently calculated quantile table and a package boxplot can legitimately disagree unless conventions are aligned.

Quantiles are resistant to changing one extreme value because they depend mainly on order positions, but they are not immune to contamination. The median’s resistance is often summarized by an approximately 50% breakdown point in suitable large-sample settings: enough altered observations can move the center arbitrarily far. The phrase “robust” names a specific behavior under perturbation, not a guarantee that the statistic answers the right scientific question.

Additional practice

  1. Calculate type-7 quartiles for [0,4,8,12][0,4,8,12].
  2. If the largest observation 12 becomes 120, which quartile changes under this interpolation rule?
  3. Why should an outlier analysis preserve an audit of any exclusion?
Worked additional solutions
  1. Positions 0.750.75 and 2.252.25 yield Q1=3Q_1=3, Q3=9Q_3=9, IQR 6.
  2. Q1Q_1 stays 3; Q3=8+0.25(120−8)=36Q_3=8+0.25(120-8)=36. Small-sample interpolated quartiles can still depend on an extreme endpoint. Resistance is not complete invariance.
  3. Exclusion changes the evidence and possibly the estimand. Record the rule, reason, timing, and sensitivity of conclusions with and without the observation.

Open chapter with navigation, interactive labs, and R examples →

Lesson 08 · Week 2

When a Graph Lies Without Changing a Number

Axis choices, denominators, scales, uncertainty, and visual ethics.

Learning objectives:

  • Compare graphs using consistent baselines and units.
  • Identify visual framing that exaggerates or conceals differences.
  • Design a responsible chart for an empirical claim.

A politician presents two bars. One is twice as tall as the other. The figures represented are 51% and 49%. The graphic is not necessarily numerically false. But if the vertical axis starts at 48%, it could easily leave an impression that the data do not justify.

That is the fundamental difficulty with statistical graphics: the picture is also an argument.

First, find the denominator

Suppose one town reports 400 crashes and another reports 200. The first has more recorded crashes. But suppose the first town has ten times the residents and considerably more road travel. Counts and rates answer different questions.

Before comparing groups, identify the units: crashes per resident, per mile driven, per licensed driver, or simply total events. None of these denominators is intrinsically correct for every investigation.

Scales change the impression

In a bar chart, bar length normally represents an amount. Starting the baseline above zero can exaggerate small absolute differences. In a line chart, however, a truncated axis may legitimately reveal a small change over time, provided the scale is explicit and the interpretation does not falsely imply a dramatic absolute difference.

Logarithmic axes are useful for multiplicative change: a move from 10 to 100 and from 100 to 1,000 occupies the same vertical distance on a base-ten logarithmic scale. Do not use such an axis without explaining it, and do not interpret equal visual increments as equal arithmetic differences.

Two-dimensional symbols can be even worse. Doubling both a circle’s diameter and its height quadruples its area; a visually enlarged illustration can overstate the magnitude of the data.

Context the chart cannot supply

Every useful graphic should answer four questions. What was measured? How was it collected? Which comparisons does the graphic support? And which uncertainties remain?

If it displays estimates, show uncertainty where relevant. A graph that compares two estimates without acknowledging their precision invites overconfidence. If observations are incomplete, show the missingness or state what was excluded.

The data should remain inspectable. A table and downloadable source often complement the picture.

Worked comparison

A chart compares 98 and 102 on a baseline of 95. The displayed heights are 3 and 7, making one bar appear over twice the other. But the values themselves differ by only 4/98 ≈ 4.1% relative to the smaller value. For an ordinary quantity bar chart, restoring a zero baseline removes that visual amplification.

This does not tell us whether the 4-unit difference matters scientifically. That requires measurement, study design, context, and perhaps uncertainty intervals.

Check yourself

  1. Which denominator would help compare traffic injuries between two cities with different populations? Could you justify a different one?
  2. Why is a zero baseline especially important for ordinary bar heights?
  3. A time-series graph uses a logarithmic scale. What must the caption explain?
Worked responses
  1. Injuries per resident might be a starting point; injuries per vehicle-mile may be more appropriate for exposure to travel. The research question determines the denominator.

  2. Without it, the visible height is not proportional to the underlying quantity.

  3. Equal vertical movement represents an equal multiplicative factor, not an equal arithmetic difference.

Further reading

ASA GAISE College recommendations emphasize context, critical communication, and real data.

Audit the mapping from numbers to ink

For a bar chart, length from the baseline encodes magnitude, so a truncated baseline can magnify a small difference. A line chart can use a narrower vertical range to reveal variation, but should label that range and avoid presenting the visual slope as a unit-free effect. Axis choice is a claim about emphasis that readers should be able to inspect.

If a circular symbol’s radius is doubled to represent a doubling in count, its area quadruples. To make area proportional to count, radius must scale with the square root of count. For values 25 and 100, radii in ratio 1:2 give areas in ratio 1:4. State what a symbol encodes rather than allowing width, area, and volume to compete silently.

An uncertainty display must name its interval: sample standard deviation, standard error, confidence interval, and prediction interval convey different quantities. Two overlapping 95% intervals for separate means do not by themselves establish that a difference is nonsignificant; the uncertainty of the difference depends on both variances and their dependence. Plot the relevant contrast and its own interval where that is the question.

Further practice

  1. If area represents count, what radius ratio represents a count ratio of nine?
  2. A chart reports a rise from 98 to 102. Calculate absolute and relative changes.
  3. Why should a caption identify the denominator and missing records?
Worked further responses
  1. Radius ratio three, since area scales as radius squared.
  2. Absolute change 4; relative change 4/98≈4.0816%4/98\approx4.0816\%.
  3. Percentages and comparisons depend on who is included. Missingness or changing eligibility can alter the apparent trend without a corresponding change in the intended population.

Open chapter with navigation, interactive labs, and R examples →

Lesson 09 · Week 3

Association and Correlation

Two variables, one tempting number, and several reasons to be careful.

Learning objectives:

  • Describe a relationship using a scatterplot.
  • Interpret Pearson's sample correlation coefficient.
  • Explain how an influential observation can alter correlation without proving causation.

Suppose you measure how many hours students studied and their examination scores. If higher study time tends to accompany higher scores, the variables are associated.

Now for the critical part: that does not automatically mean the extra study time caused higher scores.

Students differ in prior preparation, difficulty of coursework, sleep, access to resources, and many other ways. Statistics can help us identify patterns. Inferring causes requires more thought.

A scatterplot preserves the pairs

A dataset containing nn pairs of observations (xi,yi)(x_i,y_i) can be drawn as a scatterplot. Each point represents a case.

A plot can suggest a positive association, negative association, curved relationship, clusters, or no obvious pattern. Before calculating a single coefficient, inspect the graph.

If the relationship is curved, a measure of linear association may summarize it poorly.

Pearson’s correlation

The sample Pearson correlation coefficient is

r=∑i=1n(xi−xˉ)(yi−yˉ)∑i=1n(xi−xˉ)2 ∑i=1n(yi−yˉ)2.r=\frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})} {\sqrt{\sum_{i=1}^{n}(x_i-\bar{x})^2\,\sum_{i=1}^{n}(y_i-\bar{y})^2}}.

For nonconstant paired data, rr lies between −1-1 and 11.

  • Near +1+1 indicates a strong positive linear association.
  • Near −1-1 indicates a strong negative linear association.
  • Near 00 indicates weak linear association; there might still be a pronounced nonlinear relationship.

Correlation is unchanged if we add a constant to either variable or multiply both by positive constants. It is not immune to outliers.

If either variable has zero variability, Pearson correlation is undefined. There is simply no direction of linear covariation to standardize.

The case of one surprising observation

Imagine seven observations following a clear upward trend. Now add an eighth observation very far above or below the trend.

That one observation can change the correlation dramatically. A statistic summarizing the entire sample may look convincing even when one data point exerts disproportionate influence.

Try the laboratory below. Move the last observation vertically, keeping the first seven fixed. Watch the graph and the correlation value together.

In a real analysis, this would be a reason to investigate data collection, fit diagnostics, and the scientific context—not to discard a point because the result is inconvenient.

A final warning

A correlation between ice cream sales and swimming-related emergencies might be associated with season or temperature rather than ice cream causing emergencies. An observational association alone cannot identify the correct causal explanation.

We will return to causal interpretation, confounding, and regression in the later modeling unit. For now, the most important habit is simple: look at the paired data before telling a story about the coefficient.

Check your understanding

  1. If one variable is constant, what happens to Pearson’s rr?
  2. Does r=0r=0 necessarily imply the variables are independent?
  3. If moving one point greatly changes rr, what should the analyst do next?
Suggested responses
  1. It is undefined. 2. No: relationships can be nonlinear, and zero correlation alone does not imply independence. 3. Examine the point, data quality, plots, model assumptions, and substantive context; do not remove it reflexively.

Centering, scaling, and the limits of a single number

Define Sxx=∑(xi−xˉ)2S_{xx}=\sum(x_i-\bar x)^2, Syy=∑(yi−yˉ)2S_{yy}=\sum(y_i-\bar y)^2, and Sxy=∑(xi−xˉ)(yi−yˉ)S_{xy}=\sum(x_i-\bar x)(y_i-\bar y). Pearson’s correlation is r=Sxy/SxxSyyr=S_{xy}/\sqrt{S_{xx}S_{yy}}, provided both sums of squares are positive. Cauchy–Schwarz gives ∣r∣≤1|r|\leq1. If either variable is constant, the denominator is zero and correlation is undefined, not zero.

For pairs (−1,1),(0,0),(1,1)(-1,1),(0,0),(1,1), the response is exactly y=x2y=x^2. Yet Sxy=0S_{xy}=0, so r=0r=0. Zero linear correlation does not imply absence of a relationship. A scatterplot should precede or accompany the coefficient.

Adding a constant to a variable leaves correlation unchanged. Multiplying one variable by a positive constant leaves it unchanged; multiplying by a negative constant reverses its sign. Thus changing centimetres to metres does not change rr, while reversing a scale’s orientation can. The regression slope changes magnitude under unit changes because it has response-per-predictor units; correlation is dimensionless.

Additional practice

  1. Compute rr for (1,2),(2,4),(3,6)(1,2),(2,4),(3,6).
  2. What is rr if every response in those pairs is negated?
  3. Why can a single influential point increase or decrease rr dramatically in a small sample?
Worked additional solutions
  1. The points lie exactly on a line with positive slope, giving r=1r=1; direct centered sums give the same result.
  2. r=−1r=-1.
  3. The coefficient uses all centered cross-products and squared deviations. A distant point can dominate those sums. Investigate its provenance and scientific role rather than deleting it merely to obtain a preferred coefficient.

Open chapter with navigation, interactive labs, and R examples →

Unit 2

Sampling, probability, and distributions

Lesson 10 · Week 3

Sampling, Bias, and Uncertainty

Why the way we choose observations determines what we can learn.

Learning objectives:

  • Distinguish sampling variation from selection bias.
  • Explain why random sampling supports inference.
  • Recognize why increasing sample size does not automatically remove bias.

Imagine a town with 100,000 residents. We want to know what fraction supports a new park. We cannot ask everyone, so we select a thousand people.

An intelligent question is not just how many people did we ask? It is how did those people end up in our sample?

Random sampling and the big idea

In a simple random sample of size nn, every possible group of nn members of the population has an equal chance of being selected.

This does not guarantee that our sample is perfectly representative. By chance alone, it could contain more supporters than opponents. But it gives us a defined random mechanism with which to reason about uncertainty.

If we repeatedly draw random samples, their statistics will differ. This is sampling variability. It remains even when the selection process is impeccable.

Bias is a different problem

Now imagine taking our survey exclusively outside a meeting of people campaigning for the park. Even if we survey ten thousand attendees, we should not expect their answers to represent the town.

That is selection bias. It is not cured simply by collecting more of the wrong observations.

Another concern is nonresponse bias. Even if we select residents randomly, people who do not respond may differ systematically from those who do.

Bias and random error are different concepts. Random sampling error tends to diminish with larger samples, under appropriate conditions. Systematic bias need not.

Try the accompanying response-selection laboratory. The town’s opinions stay fixed. Only the relative probability that two groups respond changes, shifting the expected survey percentage without changing the population percentage. The display reports mathematical expectations, not a simulated or real opinion poll.

Why the square root keeps appearing

For independent, identically distributed observations with finite population variance σ2\sigma^2, the sample mean has standard error

SE(Xˉ)=σn.\mathrm{SE}(\bar X)=\frac{\sigma}{\sqrt{n}}.

Doubling a sample does not halve its standard error. To halve the standard error, we generally need four times as many observations.

That relationship is crucial to understanding surveys, clinical studies, and other evidence-based claims. There can be enormous costs associated with modest improvements in precision.

Real survey designs often require adjustments for clustering, weighting, finite populations, and other departures from the ideal model.

Correlation is not randomization

Random sampling helps us learn about a population. Random assignment in an experiment helps us compare interventions by breaking systematic relationships between treatment assignment and potential outcomes.

These ideas are related, but they solve different problems. We can have an experiment with random assignment and a convenience sample, or a representative survey with no experimental intervention.

Check your understanding

  1. What happens to the standard error of a sample mean if nn increases from 100 to 400?
  2. Can an enormous convenience sample have a very small calculated standard error and still be seriously biased?
  3. What is the difference between randomly selecting study participants and randomly assigning treatments?
Suggested responses
  1. It is halved under the stated model. 2. Yes; the formula for random variability does not eliminate systematic selection bias. 3. The first concerns generalizing to a population, the second concerns making fair comparisons between treatments.

Separate variance, bias, and mean squared error

For an estimator TT of a fixed parameter θ\theta, its bias is E[T]−θE[T]-\theta under a specified repetition model. Expanding the square around E[T]E[T] gives

E[(T−θ)2]=Var⁡(T)+Bias⁡(T)2.E[(T-\theta)^2]=\operatorname{Var}(T)+\operatorname{Bias}(T)^2.

Larger independent samples can reduce variance while leaving a recruitment bias untouched. A precise estimate of the wrong target can therefore have substantial mean squared error. “Unbiased” is a repeated-procedure property, not a statement that every realized sample estimate is correct.

For simple random sampling without replacement from a finite population of size NN, an estimated mean’s variance includes a finite-population correction. Using population variance defined with denominator N−1N-1, it is (1−n/N)S2/n(1-n/N)S^2/n. The corresponding standard-error factor is 1−n/N\sqrt{1-n/N}. Sampling nearly everyone leaves little sampling uncertainty, although measurement error and nonresponse can remain. The familiar independent-with-replacement expression is a useful approximation when the sampling fraction is small.

Additional practice

  1. Estimator A has variance 4 and bias 3; estimator B has variance 10 and zero bias. Compare mean squared errors.
  2. Under an independent mean model, how much must sample size increase to reduce standard error by a factor of five?
  3. If half a finite population is sampled without replacement, what is the standard-error correction relative to the corresponding with-replacement formula using S2S^2?
Worked additional solutions
  1. A has MSE 4+9=134+9=13, B has MSE 10. Smaller variance alone does not determine better squared-error performance.
  2. Multiply sample size by 25.
  3. Multiply by 1/2≈0.7071\sqrt{1/2}\approx0.7071, under the simple-random-sampling assumptions.

Open chapter with navigation, interactive labs, and R examples →

Lesson 11 · Week 3

How We Choose a Sample Changes the Mathematics

Simple random, stratified, cluster, systematic sampling and design effects.

Learning objectives:

  • Distinguish simple random, stratified, cluster, and systematic sampling.
  • Explain why unequal selection probabilities require attention.
  • Recognize when a naive independent-sample standard error is inappropriate.

Suppose we want to survey a school district with forty schools. It would be convenient to visit two schools, interview everyone there, and call the result a district survey.

That might work for some questions. But the students in a school often resemble one another more than they resemble students at another school. Convenience is not a sampling design.

Simple random and stratified samples

In a simple random sample of size nn, every set of nn population units has the same chance of selection.

In a stratified sample, we divide the population into defined groups (strata) and draw probability samples separately from each. If the strata are meaningful—say, elementary versus high schools—this can ensure each is represented and may improve precision.

However, oversampling one stratum means its raw sample percentage cannot necessarily be used as the overall population percentage. Appropriate design weights may be needed.

Cluster sampling

A cluster sample selects groups, such as schools, then studies all or some units inside the selected groups. This can be much cheaper than visiting hundreds of dispersed locations.

But outcomes within one cluster may be correlated. A sample of 500 students from two schools does not necessarily supply as much independent information as 500 students sampled across the district.

Under common approximations for equally sized clusters, the design effect can be related to cluster size mm and intracluster correlation ρ\rho:

DEFF⁡≈1+(m−1)ρ.\operatorname{DEFF}\approx1+(m-1)\rho.

For m=25m=25 and ρ=.10\rho=.10, this approximation gives 1+24(.10)=3.41+24(.10)=3.4. The standard error can be roughly 3.4\sqrt{3.4} times an independent-sample calculation under the corresponding conditions.

This is a teaching approximation, not a universal survey-analysis formula.

Systematic selection and nonresponse

Selecting every tenth name from an ordered list can be useful when the starting point is randomized. But if the list has periodic structure, systematic sampling can produce unexpected bias.

Even a beautifully designed probability sample faces nonresponse. People may answer at different rates, and missing respondents may differ in the outcome itself. We explored that in the selection bias laboratory.

What a useful survey report must say

Describe the target population, frame, sample design, selection probabilities, response rate, weighting, missingness, and uncertainty method. “Surveyed 5,000 people” does not tell us whether those people are representative.

Check yourself

  1. What is one advantage of stratifying by school level?
  2. Why might two schools with 500 respondents require a different variance calculation than a simple random sample of 500 students?
  3. What is the approximate design effect when m=11m=11 and ρ=.05\rho=.05 under the simplified formula?
Worked responses
  1. It ensures each school level contributes observations and can reduce variability within strata.

  2. Students within schools may share characteristics; clustering reduces independent information.

  3. 1+(11−1)(.05)=1.51+(11-1)(.05)=1.5.

Weights change the target of a sample mean

Suppose a target population is 80% group A and 20% group B, but a stratified sample deliberately selects 50 from each. If observed group means are 10 and 30, the unweighted mean is 20. The population-composition estimate is 0.8(10)+0.2(30)=140.8(10)+0.2(30)=14. Both summarize numbers correctly, but they target different mixtures. Report the population weights, their source, and the sampling design.

For independent simple random samples within strata, an estimated variance of μ^=∑hWhxˉh\hat\mu=\sum_hW_h\bar x_h is ∑hWh2(1−nh/Nh)sh2/nh\sum_hW_h^2(1-n_h/N_h)s_h^2/n_h, where Wh=Nh/NW_h=N_h/N and the finite-population correction reflects sampling without replacement. Neglecting the correction may be reasonable when fractions are small, but ignoring weights and design altogether is a different and often consequential approximation.

For roughly equal cluster size mm and intracluster correlation ρ\rho, the approximation DEFF=1+(m−1)ρDEFF=1+(m-1)\rho compares variance with an independent-sample reference. If 100 observations have design effect 2.5, a rough effective sample size is 40 and the standard-error inflation is 2.5≈1.581\sqrt{2.5}\approx1.581. This is a planning approximation, not a universal formula for arbitrary weights, unequal clusters, or all statistics.

Inverse-probability weights require meaningful inclusion probabilities and an appropriate sampling frame. Calibration to known margins cannot guarantee correction for every unmeasured nonresponse mechanism. Extreme weights can increase variance, so a weighted estimate needs an uncertainty calculation that respects its construction.

Further problems

  1. A population is 30% A and 70% B, with estimated stratum means 5 and 15. Find the composition-weighted mean.
  2. Under the equal-cluster approximation, find design effect for m=10m=10, ρ=0.2\rho=0.2.
  3. Why are many pupils from two classrooms not equivalent to the same number from many independently selected classrooms?
Worked further solutions
  1. 0.3(5)+0.7(15)=120.3(5)+0.7(15)=12.
  2. 1+9(0.2)=2.81+9(0.2)=2.8.
  3. Shared classroom influences create within-cluster dependence. Additional pupils may supply less independent information than additional classrooms.

Open chapter with navigation, interactive labs, and R examples →

Lesson 12 · Week 4

Probability Is a Model, Not a Prophecy

Events, complements, independence, and how to describe uncertainty without pretending to know the future.

Learning objectives:

  • Define an event, sample space, and probability under a specified model.
  • Apply complement and addition rules to simple problems.
  • Distinguish independent events from mutually exclusive events.

Suppose we toss a coin and it lands heads. What was the probability of that outcome?

You might be tempted to say 50 percent. But that answer rests on an assumption: the coin is fair, it was tossed in a particular way, and our model treats the toss as random. A heavily weighted coin would not have the same probabilities.

Probability is a mathematical description of uncertainty under specified assumptions. It is not a guarantee that reality will behave exactly as expected over a handful of observations.

What counts as an outcome?

A sample space, often written Ω\Omega, lists the possible outcomes of an experiment. For a single coin toss, Ω={H,T}\Omega=\{H,T\}. An event is a collection of outcomes. In a toss of two coins, the event “at least one head” consists of HHHH, HTHT, and THTH.

For an event AA, we assign a probability P(A)P(A) satisfying

0≤P(A)≤1,P(Ω)=1.0\leq P(A)\leq 1,\qquad P(\Omega)=1.

For mutually exclusive events, the probability of their union is the sum of their probabilities.

Under our fair-coin model, all four two-toss outcomes are equally likely, so the probability of at least one head is 3/43/4.

But notice what made the calculation possible: the model assigning equal probability to the four outcomes.

Complements are often easier

The complement of event AA, written AcA^c, is everything in the sample space that is not in AA.

P(Ac)=1−P(A).P(A^c)=1-P(A).

For example, if each of five independent tosses has a one-half chance of tails, the probability of at least one head is easiest to obtain by subtracting the probability of all tails:

P(at least one head)=1−(12)5=3132.P(\text{at least one head})=1-\left(\frac12\right)^5=\frac{31}{32}.

This does not mean that five tosses are guaranteed to include a head. It means the all-tails outcome has probability 1/321/32 under the model.

Addition and overlap

For arbitrary events AA and BB,

P(A∪B)=P(A)+P(B)−P(A∩B).P(A\cup B)=P(A)+P(B)-P(A\cap B).

That subtraction prevents us from counting the intersection twice.

If 40 percent of a group likes tea, 35 percent likes coffee, and 15 percent likes both, then 60 percent likes tea or coffee (or both):

.40+.35−.15=.60..40+.35-.15=.60.

Independent is not mutually exclusive

Two events are independent if knowing that one occurred does not change the probability of the other:

P(A∩B)=P(A)P(B).P(A\cap B)=P(A)P(B).

Two events are mutually exclusive if they cannot both happen:

P(A∩B)=0.P(A\cap B)=0.

These are very different ideas. Drawing a heart and drawing a spade on a single card draw are mutually exclusive, not independent. If one happened, the other definitely did not.

Repeated independent fair-coin tosses are independent by the model’s assumptions, but outcomes on different tosses can both be heads.

Exercise

  1. In three independent fair-coin tosses, what is the probability of at least one tail?
  2. Events AA and BB have probabilities .6 and .3, with overlap .2. Find P(A∪B)P(A\cup B).
  3. Can two events with positive probability be both independent and mutually exclusive?
Worked answers
  1. Subtract the all-heads probability: 1−(1/2)3=7/81-(1/2)^3=7/8.

  2. 0.6+0.3−0.2=0.70.6+0.3-0.2=0.7.

  3. No. Mutual exclusivity requires P(A∩B)=0P(A\cap B)=0, but independence with positive probabilities requires P(A∩B)=P(A)P(B)>0P(A\cap B)=P(A)P(B)>0.

Read further

The free OpenStax probability chapter provides additional examples and exercises.

State the probability model before using its rules

A sample space lists possible outcomes; events are subsets of that space; a probability assignment is nonnegative, totals one, and adds over disjoint events. For a finite equally likely sample space, probability is favorable-count divided by total-count. Equal likelihood is an assumption, not something established by naming outcomes.

For synthetic events A and B with probabilities 0.4 and 0.5 and intersection probability 0.1, inclusion–exclusion gives P(A∪B)=0.8P(A\cup B)=0.8. The chance neither occurs is 0.20.2. The conditional probability P(A∣B)=0.1/0.5=0.2P(A\mid B)=0.1/0.5=0.2, so these events are not independent. Simply multiplying 0.4 by 0.5 would impose a different intersection model.

For independent repetitions of an event with probability pp, the chance of at least one occurrence in nn trials is 1−(1−p)n1-(1-p)^n. With p=0.1p=0.1 and n=3n=3, it is 0.2710.271, not 0.30.3. Adding the single-event probabilities double-counts outcomes containing multiple occurrences. Without independence, the complement formula still holds but the product for the no-occurrence probability may fail.

Additional practice

  1. If P(A)=0.6P(A)=0.6, P(B)=0.5P(B)=0.5, and P(A∩B)=0.3P(A\cap B)=0.3, calculate union probability and test independence.
  2. Can two positive-probability mutually exclusive events be independent?
  3. Give a model assumption needed to interpret a coin probability as a long-run experimental frequency.
Worked additional solutions
  1. Union 0.80.8; the intersection equals 0.6(0.5)0.6(0.5), so the pair is independent.
  2. No. Their intersection is zero, whereas the product is positive.
  3. Specify a stable repeated-trial mechanism, with suitable independence or dependence assumptions for the long-run theorem being used. A single toss cannot validate that mechanism.

Open chapter with navigation, interactive labs, and R examples →

Lesson 13 · Week 4

How Many Ways Could This Happen?

Multiplication rules, combinations, permutations, and the binomial coefficient.

Learning objectives:

  • Use the multiplication principle for ordered selections.
  • Distinguish permutations from combinations.
  • Compute probabilities by counting equally likely outcomes when justified.

Twenty coin tosses have a million or so possible sequences. Yet when we ask how many contain exactly ten heads, counting each sequence by hand becomes an irritating way to spend an afternoon.

Fortunately, mathematicians noticed this problem before we did.

Multiply when decisions happen in stages

If there are three shirt choices and four independent trouser choices, there are 3×4=123\times4=12 outfits. The multiplication principle counts a sequence of decisions when each step has a specified number of options.

If repetition is allowed, selecting a four-digit PIN with digits 0–9 gives 104=10,00010^4=10,000 possible strings. If digits must be distinct, the count is 10×9×8×7=5,04010\times9\times8\times7=5,040.

These count ordered selections. The sequence 1234 is not the same PIN as 4321.

Order sometimes does not matter

A committee containing Alice and Bob is the same committee regardless of which name we write first. Selecting kk people from nn without caring about order is counted by a combination:

(nk)=n!k!(n−k)!.\binom nk=\frac{n!}{k!(n-k)!}.

A factorial n!n! is the product of positive integers through nn, with 0!=10!=1.

For eight volunteers selecting a four-person experimental group,

(84)=8!4!4!=70.\binom84=\frac{8!}{4!4!}=70.

That number was the entire reference distribution for our exact randomization laboratory.

Return to the coin

Each sequence of 20 independent fair tosses has probability 2−202^{-20}. For exactly ten heads, the heads can occupy any choice of ten of the twenty positions. Therefore,

P(X=10)=(2010)2−20.P(X=10)=\binom{20}{10}2^{-20}.

The probability calculation is valid under the fair independent-toss model. It would be a mistake to use equal sequence probabilities for a biased coin without modification.

Counting isn’t always the best tool

When events overlap, naive addition double-counts. With sampling without replacement, probabilities change after each draw. Sometimes conditional probability or simulation is more direct than heroic combinatorics.

Counting rules serve a model; they do not excuse us from specifying the model.

Check yourself

  1. How many three-letter codes can be made from A–Z if repetition is allowed?
  2. In how many ways can three people be chosen from seven when order doesn’t matter?
  3. Why is (103)\binom{10}{3} relevant to the probability of exactly three heads in ten fair tosses?
Worked responses
  1. 263=17,57626^3=17,576.

  2. (73)=35\binom73=35.

  3. It counts which three toss positions contain heads. Each specific sequence has probability 2−102^{-10}.

Derive combinations and distinguish sampling models

For kk distinct selections from nn objects, ordered selection without replacement gives n(n−1)⋯(n−k+1)=n!/(n−k)!n(n-1)\cdots(n-k+1)=n!/(n-k)! possibilities. Each unordered subset appears in k!k! different orders. Dividing gives (nk)\binom nk. The reasoning, not the factorial button, determines when the formula applies.

Suppose a fictional box contains 5 red and 7 blue counters. Draw 4 without replacement. Every four-counter subset is equally likely under simple random drawing, and exactly two red counters can be chosen in (52)(72)\binom52\binom72 ways. Therefore

P(X=2)=(52)(72)(124)=210495=1433≈0.42424.P(X=2)=\frac{\binom52\binom72}{\binom{12}4}=\frac{210}{495}=\frac{14}{33}\approx0.42424.

This is a hypergeometric calculation. A binomial model with success probability 5/125/12 would instead assume replacement or independent trials with constant success probability. Without replacement, the chance of a red counter on the next draw changes with what has already been removed. Independence is a probability assumption; the ability to count outcomes does not create it.

For a binomial count, (nk)\binom nk counts the possible positions of kk successes in nn trials. Each particular sequence has probability pk(1−p)n−kp^k(1-p)^{n-k} under independent constant-probability trials. Multiplying gives the binomial mass function. “There are two outcomes” does not imply they are equally probable, nor does it establish independence.

Further problems

  1. How many ordered three-letter strings can be formed from five distinct letters without repetition? How many unordered three-letter subsets?
  2. In the counter example, calculate the probability all four are blue.
  3. Why does shuffling an existing sample not create new independent participants?
Worked further solutions
  1. 5⋅4⋅3=605\cdot4\cdot3=60 strings and (53)=10\binom53=10 subsets.
  2. (74)/(124)=35/495=7/99\binom74/\binom{12}4=35/495=7/99.
  3. It changes ordering, not the units observed or their data-generating dependence. Randomization of labels and independent data collection are different operations.

Open chapter with navigation, interactive labs, and R examples →

Lesson 14 · Week 4

When Knowing One Thing Changes Another

Conditional probability, tree diagrams, independence, and law of total probability.

Learning objectives:

  • Compute conditional probabilities from joint counts.
  • Apply the law of total probability across a partition.
  • Check independence instead of confusing it with mutually exclusive events.

A survey finds that 60% of residents use public transit. Of transit users, 30% commute before 7 a.m.; of nonusers, only 10% do. What fraction of all residents commute that early?

The answer is not 30% and not 10%. We must weight both subgroups.

Conditional probabilities live inside denominators

If TT denotes transit use and EE denotes early commuting, then

P(E∣T)=P(E∩T)P(T).P(E\mid T)=\frac{P(E\cap T)}{P(T)}.

It means among transit users, what fraction commute early? Changing what we condition on changes the denominator and therefore the question.

Weighted branches

Partition the population by transit use:

P(E)=P(E∣T)P(T)+P(E∣Tc)P(Tc).P(E)=P(E\mid T)P(T)+P(E\mid T^c)P(T^c).

Using the fictional percentages gives

P(E)=.30(.60)+.10(.40)=.22.P(E)=.30(.60)+.10(.40)=.22.

So 22% commute early. A probability tree makes the same calculation visible: multiply along branches, then add disjoint branches ending in the event we care about.

This is called the law of total probability.

Check independence

Two events AA and BB are independent when

P(A∣B)=P(A)P(A\mid B)=P(A)

when conditioning is defined. Equivalently, P(A∩B)=P(A)P(B)P(A\cap B)=P(A)P(B).

In our example, P(E∣T)=.30P(E\mid T)=.30 but P(E)=.22P(E)=.22. The events are not independent. Knowing transit use changes the probability of early commuting.

Compare this with mutually exclusive events, which cannot happen together. A person cannot be simultaneously classified in two nonoverlapping transit categories, but the category and an early commute can certainly co-occur.

Why this matters for Bayesian reasoning

Bayes’ theorem reverses a conditional question by using the probability of the evidence across possible explanations. The base-rate laboratory is a probability tree in disguise: disease/no disease branches, followed by positive/negative test branches.

Always label which conditional probability each percentage represents. Sensitivity is not positive predictive value.

Check yourself

  1. Find the probability that a resident both uses transit and commutes early.
  2. If everyone commuted early at the same rate regardless of transit, what equality would hold?
  3. Why can you add P(E∩T)P(E\cap T) and P(E∩Tc)P(E\cap T^c) without subtracting an overlap?
Worked responses
  1. .60(.30)=.18.60(.30)=.18.

  2. P(E∣T)=P(E∣Tc)=P(E)P(E\mid T)=P(E\mid T^c)=P(E), assuming both groups have positive probability.

  3. Transit use and nonuse are disjoint events that partition the population.

Build the entire joint table

For 1,000 hypothetical residents, the stated percentages correspond to the following expected counts:

Early Not early Total
Transit 180 420 600
No transit 40 360 400
Total 220 780 1000

Thus P(T∣E)=180/220=9/11≈0.81818P(T\mid E)=180/220=9/11\approx0.81818, whereas P(E∣T)=180/600=0.30P(E\mid T)=180/600=0.30. Conditioning in the other direction changes the denominator. The joint probability 0.180.18 is the same intersection whichever event is named first, but the conditional probabilities are not interchangeable.

For a partition B1,…,BkB_1,\ldots,B_k with positive probabilities, P(A)=∑iP(A∣Bi)P(Bi)P(A)=\sum_iP(A\mid B_i)P(B_i). This follows by splitting AA into disjoint intersections A∩BiA\cap B_i and applying the multiplication rule. Bayes then divides one of those intersections by their total: P(Bj∣A)=P(A∣Bj)P(Bj)/P(A)P(B_j\mid A)=P(A\mid B_j)P(B_j)/P(A) when P(A)>0P(A)>0.

Pairwise independence is weaker than mutual independence for three or more events. Toss two fair independent coins. Let A mean the first is heads, B the second is heads, and C mean the two agree. Each pair is independent, yet P(A∩B∩C)=1/4P(A\cap B\cap C)=1/4, not (1/2)3(1/2)^3. Conditioning on two events can reveal a dependence invisible in pairwise checks.

Further problems

  1. From the table, compute P(T∣Ec)P(T\mid E^c).
  2. If P(A)=0.4P(A)=0.4, P(B)=0.5P(B)=0.5, and P(A∩B)=0.2P(A\cap B)=0.2, are A and B independent? Mutually exclusive?
  3. Why is conditioning on an event of probability zero not defined by the elementary ratio formula?
Worked further solutions
  1. 420/780=7/13≈0.53846420/780=7/13\approx0.53846.
  2. They are independent because the intersection equals the product. They are not mutually exclusive because the intersection probability is positive.
  3. The denominator would be zero. Conditional distributions at particular values of continuous variables require more advanced definitions than this elementary event formula.

Open chapter with navigation, interactive labs, and R examples →

Lesson 15 · Week 5

Bayes' Theorem and the Base-Rate Trap

Why a test can be highly accurate and still produce many false alarms.

Learning objectives:

  • Calculate a conditional probability using Bayes' theorem.
  • Distinguish sensitivity from positive predictive value.
  • Explain why the prevalence of an event changes the meaning of new evidence.

A medical screening test is described as “90 percent accurate.” Is a positive result a 90 percent chance that you have the condition?

Not necessarily. In fact, that inference can be wrong by a remarkable amount. The trouble is that there are two different conditional probabilities, and reversing them changes the question.

We will use a fictional test and hypothetical numbers rather than make any claims about a real disease.

Conditional probability changes the sample space

For events AA and BB with P(B)>0P(B)>0,

P(A∣B)=P(A∩B)P(B).P(A\mid B)=\frac{P(A\cap B)}{P(B)}.

Read this as “the probability of AA, given that BB occurred.”

A conditional probability does not simply tell us that two things are related. It says we are restricting attention to cases where the condition is known to hold.

For a diagnostic test, consider two distinct probabilities:

  • Sensitivity: P(+∣D)P(+\mid D), the probability of a positive test given that the condition is present.
  • Positive predictive value: P(D∣+)P(D\mid +), the probability of the condition given a positive test.

These are not the same fraction.

Enter Bayes

Bayes’ theorem gives us a way to reverse a conditional probability while accounting for how common the underlying condition is:

P(D∣+)=P(+∣D) P(D)P(+∣D) P(D)+P(+∣Dc) P(Dc).P(D\mid +)= \frac{P(+\mid D)\,P(D)} {P(+\mid D)\,P(D)+P(+\mid D^c)\,P(D^c)}.

Here P(D)P(D) is prevalence, and P(+∣Dc)P(+\mid D^c) is the false-positive rate, which equals 1−specificity1-\text{specificity}.

Suppose the hypothetical condition affects 1 percent of people. The fictional test has 90 percent sensitivity and 95 percent specificity.

Out of 10,000 screened people, we expect approximately 100 to have the condition. Around 90 of those would test positive. Of the 9,900 without the condition, about 495 would test positive anyway.

Therefore, among expected positive results,

P(D∣+)=9090+495≈0.15385.P(D\mid +)=\frac{90}{90+495}\approx 0.15385.

Just 15.4 percent, not 90 percent.

The test hasn’t failed to achieve the assumed sensitivity or specificity. The low prevalence means that even a relatively small false-positive rate generates many positives among the much larger group without the condition.

Why the base rate matters

This is the base-rate problem. The same evidence can carry a different meaning in populations where the underlying condition is more or less common.

Change the prevalence in the laboratory below while leaving sensitivity and specificity untouched. Notice how the positive predictive value moves.

This is equally relevant to fraud detection, spam filtering, equipment fault monitoring, and other settings where we attempt to detect rare events.

What this example does not imply

The example does not recommend screening, diagnosis, or treatment for anyone. Real tests have different characteristics in different populations and settings. Sampling, verification, selection, and measurement also matter.

The lesson is narrower and more general: when interpreting evidence, remember how probable the underlying event was before the evidence arrived.

Exercise

  1. For a hypothetical test with 80 percent sensitivity, 90 percent specificity, and 10 percent prevalence, find P(D∣+)P(D\mid +).
  2. Is a 99 percent specificity equivalent to a 99 percent positive predictive value?
  3. Why might the same positive test have different predictive values in two populations?
Worked answers
  1. The true-positive portion is .1(.8)=.08.1(.8)=.08, and the false-positive portion is .9(.1)=.09.9(.1)=.09. Thus .08/(.08+.09)≈.4706.08/(.08+.09)\approx.4706, or 47.1 percent.

  2. No. Specificity is P(−∣Dc)P(-\mid D^c), whereas positive predictive value is P(D∣+)P(D\mid +).

  3. Prevalence changes the relative numbers of true and false positives, even if sensitivity and specificity remain the same.

Read further

See the probability material in OpenStax Introductory Statistics 2e and the current ASA GAISE teaching recommendations.

Likelihood ratios update odds

For condition D and evidence E, Bayes can be written

P(D∣E)P(Dc∣E)=P(D)P(Dc)P(E∣D)P(E∣Dc).\frac{P(D\mid E)}{P(D^c\mid E)} =\frac{P(D)}{P(D^c)}\frac{P(E\mid D)}{P(E\mid D^c)}.

The last factor is the likelihood ratio. For a positive screening result with sensitivity 0.90 and specificity 0.95, it is 0.90/0.05=180.90/0.05=18. At prevalence 0.01, prior odds are 1/991/99, so posterior odds are 18/99=2/1118/99=2/11 and posterior probability is (2/11)/(1+2/11)=2/13≈0.153846(2/11)/(1+2/11)=2/13\approx0.153846.

A hypothetical population of 10,000 makes the denominators tangible: 100 have the condition, with 90 expected positive results. Among 9,900 without it, 495 expected results are positive. Thus 90 of 585 expected positives correspond to the condition. These are model-based expected counts, not guaranteed realized counts or a report about a particular medical test.

Repeated positive results cannot automatically be treated as independent evidence. Multiplying the same likelihood ratio twice assumes the second test is conditionally independent of the first given condition status, or otherwise has the specified conditional evidence ratio. Shared specimen contamination or correlated errors can violate that assumption. An apparently stronger posterior can therefore be a consequence of an unjustified dependence model.

Additional practice

  1. With prevalence 0.10 and the same sensitivity and specificity, calculate positive predictive value.
  2. If prior odds are 1/41/4 and the evidence likelihood ratio is 3, calculate posterior probability.
  3. Why is this worked probability model not individualized medical advice?
Worked additional solutions
  1. 0.09/[0.09+0.05(0.9)]=2/30.09/[0.09+0.05(0.9)]=2/3.
  2. Posterior odds 3/43/4, so probability 3/73/7.
  3. The inputs are hypothetical and omit clinical context, uncertainty in accuracy, and dependence. The example teaches conditional probability, not a decision for an actual patient.

Open chapter with navigation, interactive labs, and R examples →

Lesson 16 · Week 5

The Long-Run Average Is Not a Promise

Expected value, variance, linear transformations, and why risk needs a spread.

Learning objectives:

  • Calculate the expectation of a discrete random variable.
  • Compute variance and standard deviation from a distribution.
  • Distinguish variability from the expected value.

You are offered a game. With probability one-half you win 10 dollars; otherwise you lose 8 dollars. Would you play?

The average outcome over many plays is positive. But that does not mean you’ll win one dollar on your next attempt.

Expected value is probability-weighted

For discrete outcomes xix_i with probabilities pip_i,

E[X]=∑ixipi.E[X]=\sum_i x_i p_i.

For this game,

E[X]=10(.5)+(−8)(.5)=1.E[X]=10(.5)+(-8)(.5)=1.

The expected gain is one dollar per play. In a single play the gain is either 10 dollars or a loss of 8 dollars; the expected value is not even a possible outcome.

Variance describes the spread

Expectation alone tells us little about risk. A game that always pays one dollar and a game that pays 1,001 dollars or loses 999 dollars with equal probabilities both have expectation one dollar. Their variability is rather different.

The population variance of a discrete random variable is

Var⁡(X)=E[(X−E[X])2]=∑ipi(xi−μ)2.\operatorname{Var}(X)=E[(X-E[X])^2] =\sum_i p_i(x_i-\mu)^2.

For the first game with mean 11, deviations are 99 and −9-9. Variance is 8181 and standard deviation is 99.

A useful computational shortcut is Var⁡(X)=E[X2]−E[X]2\operatorname{Var}(X)=E[X^2]-E[X]^2.

Units and linear transformations

For constants aa and bb,

E[a+bX]=a+bE[X],Var⁡(a+bX)=b2Var⁡(X).E[a+bX]=a+bE[X],\quad \operatorname{Var}(a+bX)=b^2\operatorname{Var}(X).

Adding ten dollars changes the mean by ten but leaves the spread unchanged. Multiplying dollar amounts by two doubles the standard deviation and quadruples the variance.

If XX and YY are independent, the variance of their sum is the sum of their variances. Without independence, a covariance term is required. Don’t silently assume independence because it makes a formula convenient.

A binomial connection

For X∼Binomial(n,p)X\sim\mathrm{Binomial}(n,p), expectation is npnp and variance is np(1−p)np(1-p), derived from a sum of independent Bernoulli indicators.

Check yourself

  1. If XX equals 0 with probability .75 and 8 with probability .25, find E[X]E[X].
  2. Find the variance and standard deviation of that variable.
  3. If all values are multiplied by three, what happens to the variance?
Worked responses
  1. E[X]=2E[X]=2.

  2. Variance is .75(0−2)2+.25(8−2)2=12.75(0-2)^2+.25(8-2)^2=12, so the standard deviation is 12≈3.464\sqrt{12}\approx3.464.

  3. It is multiplied by 32=93^2=9.

Derive the variance identities

Expanding the centered square gives E[(X−μ)2]=E[X2]−2μE[X]+μ2=E[X2]−μ2E[(X-\mu)^2]=E[X^2]-2\mu E[X]+\mu^2=E[X^2]-\mu^2, assuming the second moment is finite. This identity is algebraically convenient, but direct subtraction of two nearly equal large values can lose floating-point accuracy. Computing centered deviations is often numerically safer.

Linearity of expectation does not require independence: E[X+Y]=E[X]+E[Y]E[X+Y]=E[X]+E[Y] whenever the expectations are defined appropriately. Variance does require attention to dependence:

Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)+2Cov⁡(X,Y).\operatorname{Var}(X+Y)=\operatorname{Var}(X)+\operatorname{Var}(Y)+2\operatorname{Cov}(X,Y).

For a difference the covariance term has a minus sign. If Y=XY=X, the sum is 2X2X and its variance is 4Var⁡(X)4\operatorname{Var}(X), not twice the variance. Independence is sufficient for zero covariance when moments exist, but zero covariance need not imply independence. For example, a symmetric variable XX and Y=X2Y=X^2 can have zero covariance despite a deterministic relationship.

A Bernoulli indicator II equals one for success and zero otherwise. Since I2=II^2=I, E[I]=pE[I]=p and Var⁡(I)=p−p2\operatorname{Var}(I)=p-p^2. A binomial count is the sum of nn independent indicators with the same success probability, giving mean npnp and variance np(1−p)np(1-p). For the sample proportion X/nX/n, the variance is p(1−p)/np(1-p)/n. This derivation explains the square-root sample-size denominator in proportion standard errors.

Further problems and solutions

  1. If E[X]=3E[X]=3 and Var⁡(X)=4\operatorname{Var}(X)=4, find the mean and variance of 10−2X10-2X.
  2. If X,YX,Y each have variance 4 and covariance 3, find the variance of their difference.
  3. Why can expected profit alone be insufficient for comparing two investments or games?
Worked further solutions
  1. Mean 44; variance (−2)2(4)=16(-2)^2(4)=16; standard deviation 44.
  2. 4+4−2(3)=24+4-2(3)=2.
  3. Equal means can accompany different tail risks, loss probabilities, and variances. The full distribution and the decision maker’s constraints matter; expectation is one summary.

Open chapter with navigation, interactive labs, and R examples →

Lesson 17 · Week 5

Random Variables and the Binomial Model

How counting successes becomes a probability distribution.

Learning objectives:

  • Identify a random variable and interpret its distribution.
  • Recognize the assumptions required for a binomial model.
  • Calculate and interpret a binomial probability and expected value.

Suppose we toss a fair coin twenty times and count the number of heads. There is no mystery about the procedure, but the count is not fixed in advance.

That count is a random variable: a numerical function of an uncertain outcome. The entire set of probabilities assigned to its possible values is its probability distribution.

Discrete random variables

Let XX be the number of heads in twenty independent, fair coin tosses. The possible values are 0,1,…,200,1,\ldots,20.

A probability mass function lists P(X=k)P(X=k) for each possible kk. Every entry is nonnegative, and all the probabilities sum to one.

The count is not equally likely to be 0 or 10. There is exactly one way to get 20 heads, but many different sequences with exactly 10 heads.

The binomial distribution

A binomial model applies when we have:

  1. A fixed number nn of trials.
  2. Exactly two relevant outcomes per trial, often called success and failure.
  3. A constant probability pp of success for each trial.
  4. Independent trials.

Then XX, the number of successes, follows a binomial distribution:

P(X=k)=(nk)pk(1−p)n−k,k=0,1,…,n.P(X=k)=\binom nk p^k(1-p)^{n-k}, \qquad k=0,1,\ldots,n.

The term (nk)\binom nk is the number of ways to arrange kk successes among nn trials.

For a fair coin, p=.5p=.5. With two tosses, the probability of exactly one head is

P(X=1)=(21)(.5)1(.5)1=2(.25)=.5.P(X=1)=\binom21(.5)^1(.5)^1=2(.25)=.5.

If you count the sequences HTHT and THTH, you get exactly the same answer.

Expected value isn’t necessarily a possible outcome

For a binomial random variable,

E[X]=np,Var⁡(X)=np(1−p).E[X]=np,\qquad \operatorname{Var}(X)=np(1-p).

The expected number of heads in twenty fair tosses is 20(.5)=1020(.5)=10, and its standard deviation is 20(.5)(.5)=5≈2.236\sqrt{20(.5)(.5)}=\sqrt5\approx2.236.

In one trial of a different experiment, the expected value might be 2.6 successes. That does not mean 2.6 successes can actually occur. An expectation is a long-run weighted average, not a promise about a single experiment.

Real data can violate the model

Imagine surveying ten people who all live in the same household. Their answers may be correlated. If we pretend their responses are independent Bernoulli trials, the simple binomial model may badly misrepresent the uncertainty.

Likewise, changing success probabilities from person to person violate the constant-pp assumption of the basic model.

Those are not small print. They are reasons to ask whether a probability model is suitable before applying it.

From probability to inference

Once we specify a binomial model, we can ask: If the coin really is fair, how surprising would a count of 18 heads in 20 tosses be?

That’s the doorway into hypothesis testing. The exact binomial test laboratory lets you explore that question. Unlike a normal approximation, it calculates the finite-sample probabilities directly.

Exercise

  1. Give the four conditions for a binomial count.
  2. What is the probability of exactly 2 heads in 3 independent fair tosses?
  3. If X∼Binomial⁡(40,.25)X\sim\operatorname{Binomial}(40,.25), what are its mean and variance?
Worked answers
  1. Fixed number of trials, two outcomes, constant success probability, independent trials.

  2. (32)(.5)3=3/8\binom32(.5)^3=3/8.

  3. Mean 40(.25)=1040(.25)=10; variance 40(.25)(.75)=7.540(.25)(.75)=7.5.

Read further

See OpenStax: Discrete Random Variables.

Derive and compute the distribution

Let IiI_i indicate success on trial ii. Under independent identical Bernoulli trials, X=∑iIiX=\sum_iI_i and

P(X=k)=(nk)pk(1−p)n−k,E[X]=np,Var⁡(X)=np(1−p).P(X=k)=\binom nkp^k(1-p)^{n-k},\quad E[X]=np,\quad\operatorname{Var}(X)=np(1-p).

For n=5n=5 and p=0.2p=0.2, exactly two successes has probability 10(0.2)2(0.8)3=0.204810(0.2)^2(0.8)^3=0.2048. At least one has probability 1−0.85=0.672321-0.8^5=0.67232. The expected count is 1 and standard deviation 0.8≈0.89443\sqrt{0.8}\approx0.89443. A count mean and a single count outcome are different objects, even when their numerical values happen to coincide.

If probabilities differ by trial while trials remain independent, the count generally follows a Poisson-binomial distribution, not this binomial formula. Sampling without replacement from a small finite population instead calls for a hypergeometric model. Dependence or changing probability must be examined before selecting a familiar mass function.

For large nn, direct factorial arithmetic can overflow. Software works with log probabilities or stable recurrences. A numerical display of zero can mean underflow rather than an impossible event. In R, dbinom(k,n,p,log=TRUE) retains log probabilities, while pbinom computes cumulative probabilities without requiring manual summation of rounded masses.

Additional practice

  1. For X∼Binomial(4,0.5)X\sim\mathrm{Binomial}(4,0.5), calculate P(X=2)P(X=2) and P(X≥3)P(X\geq3).
  2. Calculate mean and variance of X/4X/4 in that example.
  3. Why does a basketball player’s number of successes not necessarily satisfy independent constant-probability assumptions?
Worked additional solutions
  1. 6/16=0.3756/16=0.375 and (4+1)/16=0.3125(4+1)/16=0.3125.
  2. Mean 0.50.5 and variance 1/16=0.06251/16=0.0625.
  3. Skill, fatigue, defense, shot difficulty, and serial dependence may change success probability or connect outcomes. A binary outcome alone is not a binomial justification.

Open chapter with navigation, interactive labs, and R examples →

Lesson 18 · Week 5

Counting Events That Might Never Happen

Poisson counts, rates, exposure, and why independence matters.

Learning objectives:

  • State the basic Poisson count model and its parameter.
  • Calculate a zero-event probability under the model.
  • Recognize overdispersion and clustering as possible model violations.

A network operations desk averages two incident tickets an hour. What is the probability that the next hour brings no tickets?

The tempting answer is “not very likely.” Statistics demands something a little more specific.

A count model

A Poisson random variable with rate parameter λ>0\lambda>0 has probability mass function

P(X=k)=e−λλkk!,k=0,1,2,….P(X=k)=\frac{e^{-\lambda}\lambda^k}{k!},\quad k=0,1,2,\ldots.

Both its mean and variance are λ\lambda. For a one-hour observation window with an average of two events, λ=2\lambda=2.

The probability of zero events is

P(X=0)=e−2≈.1353.P(X=0)=e^{-2}\approx.1353.

That is about 13.5%, under the stated model. The average of two events does not mean every hour contains two.

Exposure changes the expected count

If the event rate is two per hour and we assume it remains constant through time, a half-hour window has λ=1\lambda=1, while a three-hour window has λ=6\lambda=6.

This rate-per-exposure interpretation is especially important when comparing counts from different periods or populations. A hospital with twice as many patient-days may record twice as many incidents even if its incidence rate is unchanged.

Where the model can fail

A Poisson process assumes a particular kind of randomly occurring event structure, including a stable rate and independent increments in its simplest form.

Network incidents may cluster during outages. Injuries may share environmental causes. Data recorded in short or long windows may have variance much larger than their mean—a phenomenon called overdispersion relative to the Poisson model.

When a dataset’s observed variance greatly exceeds its observed mean, the basic Poisson model deserves scrutiny. Negative-binomial models or explicit clustered processes may be more realistic.

Poisson as a binomial limit

A binomial count with many trials and a small success probability approaches a Poisson distribution if np→λnp\to\lambda appropriately. That makes the Poisson a useful approximation for rare, independent events across many opportunities—but only when the assumptions resemble reality.

Check yourself

  1. If X∼Poisson⁡(3)X\sim\operatorname{Poisson}(3), calculate P(X=0)P(X=0).
  2. A process averages four calls per hour. What is λ\lambda for 15 minutes under constant rate?
  3. Why might a spate of correlated outages make a simple Poisson model poor?
Worked responses
  1. e−3≈0.0498e^{-3}\approx0.0498.

  2. One expected call in a quarter hour.

  3. Dependence and clustering can violate the equal-rate independent-event structure and inflate variance.

Use base R dpois(0,3) to verify the first numerical result.

A process model and a count distribution are different claims

A homogeneous Poisson process assumes independent counts in disjoint time windows, a constant event rate, and appropriately rare single events over very short intervals. It produces a Poisson count in a window of length tt with parameter λ=rt\lambda=rt. Observing one histogram resembling a Poisson mass function does not establish independent increments or a constant rate over time.

For r=4r=4 calls per hour and a 15-minute window, λ=1\lambda=1. The probability of at least two calls is

1−P(X=0)−P(X=1)=1−e−1(1+1)≈0.26424.1-P(X=0)-P(X=1)=1-e^{-1}(1+1)\approx0.26424.

For a full hour it is 1−e−4(1+4)≈0.908421-e^{-4}(1+4)\approx0.90842. Changing the exposure changes the entire probability distribution, not just the units printed beside the parameter.

If independent Poisson counts have parameters λ1\lambda_1 and λ2\lambda_2, their sum is Poisson with parameter λ1+λ2\lambda_1+\lambda_2. A direct convolution proof expands P(X+Y=k)P(X+Y=k) and applies the binomial theorem to ∑jλ1jλ2k−j/[j!(k−j)!]\sum_j\lambda_1^j\lambda_2^{k-j}/[j!(k-j)!]. Dependence invalidates this simple sum result.

For independent equal-exposure counts, a sample variance substantially greater than the sample mean can signal overdispersion relative to a simple Poisson model. Clustering, changing rates, heterogeneous exposure, and excess zeros can all contribute. A diagnostic signal prompts model investigation; it is not an automatic proof of any one alternative.

Further problems

  1. A constant-rate model averages 3 events per hour. Find the expected count over 20 minutes and the chance of no event.
  2. If two independent Poisson streams have rates 2 and 5 per hour, what is the one-hour combined distribution?
  3. Why should days with different observation durations not be compared by raw event counts alone?
Worked further solutions
  1. Parameter 11 and probability e−1≈0.36788e^{-1}\approx0.36788.
  2. Poisson with parameter 77.
  3. Exposure affects expected counts. Compare rates or model the exposure explicitly; an increase in observation time can raise counts with no change in event intensity.

Open chapter with navigation, interactive labs, and R examples →

Lesson 19 · Week 6

Density Is Not Probability

Continuous variables, areas under curves, uniform and exponential models.

Learning objectives:

  • Distinguish density height from interval probability.
  • Calculate probabilities for uniform and exponential variables.
  • Explain why exact points have zero probability in continuous models.

A probability density can be taller than one. This surprises people who were just told that probabilities lie between zero and one.

There is no contradiction: a density is not a probability. It is a function whose area over a range gives a probability.

Probability lives in an area

For a continuous random variable with density ff,

P(a≤X≤b)=∫abf(x) dx.P(a\le X\le b)=\int_a^b f(x)\,dx.

The total area is one. The probability of one exact point is zero under an absolutely continuous distribution, even at the point where the density is tallest.

For a uniform variable between 0 and 2, f(x)=1/2f(x)=1/2 inside that interval. The probability of falling between .5 and 1.5 is the width 1 multiplied by density .5, giving .5.

A perfectly flat model

For X∼U(a,b)X\sim U(a,b), each equal-width interval inside the range has equal probability. The density is 1/(b−a)1/(b-a).

Expected value is (a+b)/2(a+b)/2 and variance is (b−a)2/12(b-a)^2/12. Uniform randomness is useful as a model and as a simulation ingredient, but many real physical measurements are anything but uniform.

Waiting for an event

In a simple Poisson process with rate λ\lambda events per unit time, the time TT until the next event has an exponential distribution:

f(t)=λe−λt, t≥0;P(T>t)=e−λt.f(t)=\lambda e^{-\lambda t},\ t\ge0;\quad P(T>t)=e^{-\lambda t}.

If the event rate is two per hour, the chance of waiting more than half an hour is e−1≈.3679e^{-1}\approx.3679.

The exponential model is memoryless: conditional on waiting already, the remaining waiting-time distribution has the same form. This is a strong modeling assumption, not a universal law of waiting rooms.

Normality is one model among many

A normal distribution also has a density, but unlike a uniform or exponential density, it has a symmetric bell shape across the real line.

We should decide which model to use from the science and observed patterns, not because one curve is easier to integrate or has appeared on more classroom slides.

Check yourself

  1. What is P(.2<X<.7)P(.2<X<.7) when X∼U(0,1)X\sim U(0,1)?
  2. Why is P(X=1)=0P(X=1)=0 for a continuous model not saying that the value can never be observed?
  3. For an exponential waiting time with rate 3/hour, calculate P(T>1 hour)P(T>1\text{ hour}).
Worked responses
  1. .7−.2=.5.7-.2=.5.

  2. A continuous model assigns probability to intervals rather than positive mass to individual exact points.

  3. e−3≈.0498e^{-3}\approx.0498.

A density is not a point probability

A probability density is nonnegative and integrates to one over its domain. Its units are inverse units of the variable, so multiplying by a small interval width produces a dimensionless approximate probability. A density can exceed one: the uniform density on [0,0.2][0,0.2] is 5, yet its total area is exactly one. For a continuous variable, P(X=x)=0P(X=x)=0 at each single point. Zero point probabilities do not imply zero probability for an interval containing uncountably many points.

For X∼U(a,b)X\sim U(a,b), E[X]=(a+b)/2E[X]=(a+b)/2 and Var⁡(X)=(b−a)2/12\operatorname{Var}(X)=(b-a)^2/12. These follow by integrating xf(x)xf(x) and (x−E[X])2f(x)(x-E[X])^2f(x). For a uniform variable on [2,8][2,8], the mean is 5 and variance 3. The chance of lying in [3,6][3,6] is its length divided by total length, 3/6=1/23/6=1/2.

For exponential waiting time with rate r>0r>0, the survival function is P(T>t)=e−rtP(T>t)=e^{-rt} for t≥0t\geq0. Consequently

P(T>s+t∣T>s)=e−r(s+t)e−rs=e−rt.P(T>s+t\mid T>s)=\frac{e^{-r(s+t)}}{e^{-rs}}=e^{-rt}.

This is the memoryless property. It is a model implication, not a universal description of waiting. Aging equipment and scheduled service intervals usually require different assumptions. The mean is 1/r1/r and variance 1/r21/r^2; doubling the rate halves expected waiting time.

The cumulative distribution function F(x)=P(X≤x)F(x)=P(X\leq x) gives interval probabilities by F(b)−F(a)F(b)-F(a) for a<ba<b in the continuous case. For a differentiable CDF, its derivative is the density. CDFs are bounded by zero and one; densities need not be.

Further problems

  1. For a uniform variable on [10,14][10,14], find mean, variance, and P(X>13)P(X>13).
  2. For an exponential rate of 2 per hour, find the chance of waiting more than another hour after already waiting two hours.
  3. Explain why a probability density of 4 at a point does not violate probability axioms.
Worked further solutions
  1. Mean 12, variance 16/12=4/316/12=4/3, and probability 1/41/4.
  2. e−2≈0.13534e^{-2}\approx0.13534, by memorylessness under the exponential model.
  3. The density is probability per unit of the variable, not a point probability. Area over an interval, not height, must lie in the probability range.

Open chapter with navigation, interactive labs, and R examples →

Lesson 20 · Week 6

The Normal Distribution

Understand bell curves, standardized values, and areas under a density.

Learning objectives:

  • Interpret the mean and standard deviation of a normal distribution.
  • Convert observations to standard scores.
  • Read a probability as area under a density curve.

You have undoubtedly seen a bell curve. It appears in discussions of exam scores, measurement error, biological traits, and rather more dubious claims about human behavior.

The curve is not automatically the right model merely because it is familiar. But when a normal distribution is appropriate, its mathematical structure makes many calculations elegant.

Where a bell curve comes from

A normally distributed random variable XX has two parameters: its mean μ\mu and standard deviation σ>0\sigma>0.

Its probability density function is

f(x)=1σ2πexp⁡[−(x−μ)22σ2].f(x)=\frac{1}{\sigma\sqrt{2\pi}} \exp\left[-\frac{(x-\mu)^2}{2\sigma^2}\right].

The mean determines the center. The standard deviation determines how wide or narrow the curve is.

The height of a density curve is not itself a probability. Probability corresponds to area under the curve. The entire area equals 1.

For a continuous random variable, the probability of any single exact value is zero. We calculate the probability of an interval instead.

Standardization

If XX is normal with mean μ\mu and standard deviation σ\sigma, the standardized variable is

Z=X−μσ.Z=\frac{X-\mu}{\sigma}.

ZZ has a standard normal distribution: mean 0 and standard deviation 1. A zz-score of 2 means an observation is two standard deviations above the mean.

For example, if exam scores are approximately normal with mean 70 and standard deviation 10, a score of 85 has

z=85−7010=1.5.z=\frac{85-70}{10}=1.5.

We can use the standard normal distribution to interpret the associated proportion of observations.

The 68–95–99.7 rule

For an exactly normal distribution, about 68% of the probability lies within one standard deviation of the mean, about 95% within two, and about 99.7% within three.

These are approximations. The commonly used interval −1.96<Z<1.96-1.96<Z<1.96 captures approximately 95% of the standard normal probability.

That does not mean every dataset contains exactly 95% of its values within 1.96 sample standard deviations. The result is a statement about an idealized probability model.

Explore the probability area

Move the slider in the laboratory to change the symmetric interval [−z,z][-z,z]. The shaded area and its approximate probability update together.

This is a model probability, not automatically a confidence interval for an unknown parameter. Later, we will examine how sampling distributions help construct confidence intervals and what their coverage really means.

Check your understanding

  1. If μ=100\mu=100 and σ=15\sigma=15, what is the zz-score of 130?
  2. What does the total area under a probability density equal?
  3. Is a tall density curve at a particular point evidence that the point itself has positive probability?
Suggested responses
      1. Exactly 1. 3. No; for a continuous distribution the probability at a single exact point is zero. Probability is associated with intervals.

Translate an applied interval to a probability statement

For X∼N(100,152)X\sim N(100,15^2), the chance of a value between 85 and 130 is

P(85<X<130)=P(−1<Z<2)=Φ(2)−Φ(−1)≈0.81859.P(85<X<130)=P(-1<Z<2)=\Phi(2)-\Phi(-1)\approx0.81859.

The standard deviation is 15, while the second distribution parameter as written is the variance 225225. Books and software use different conventions; define which one is supplied. Standardization subtracts the mean and divides by the standard deviation, producing a dimensionless variable.

An upper 5% cutoff is 100+15z.95≈124.6728100+15z_{.95}\approx124.6728, with z.95≈1.644854z_{.95}\approx1.644854. A central 95% interval uses z.975≈1.959964z_{.975}\approx1.959964 instead because 5% is split between both tails. Confusing a one-tail percentile with a two-tail interval critical value changes the answer.

The empirical 68–95–99.7 pattern is a normal-model approximation. It is not a property of every distribution with a mean and standard deviation. A normal model also assigns positive probability to every real interval; if a variable is bounded or strongly skewed, examine whether its tail predictions make sense in the application.

Additional practice

  1. Standardize 70 for a normal variable with mean 50 and standard deviation 10.
  2. Find its approximate upper-tail probability using Φ(2)≈0.97725\Phi(2)\approx0.97725.
  3. Explain the difference between a 95th percentile of individual values and a 95% confidence interval for an unknown mean.
Worked additional solutions
  1. z=(70−50)/10=2z=(70-50)/10=2.
  2. 1−0.97725=0.022751-0.97725=0.02275.
  3. The percentile describes individual variability under a distribution. A confidence interval describes uncertainty from an estimation procedure and depends on sample size and study design.

Open chapter with navigation, interactive labs, and R examples →

Lesson 21 · Week 6

The Central Limit Theorem

Watch the shape of a sampling distribution emerge from repeated experiments.

Learning objectives:

  • Differentiate the population distribution from the distribution of sample means.
  • State what the central limit theorem says under familiar conditions.
  • Explain why a larger sample can make sampling means less variable.

Here is something that sounds suspiciously like a mathematical magic trick. Start with a population that does not resemble a bell curve at all. Select random samples, calculate their averages, and repeat. The distribution of those averages will often begin to resemble a bell curve.

That is the central limit theorem. And it is one of the reasons statistical inference is possible.

First, distinguish three things

  1. The population distribution describes the individual values in the population.
  2. A sample is a set of values drawn from that population.
  3. The sampling distribution of the sample mean describes the means produced by repeatedly drawing samples of the same size.

The sampling distribution is not a histogram of all the individual observations. It is a histogram of a statistic computed once per sample.

This distinction matters. If a distribution of individual incomes is skewed, the distribution of averages across many independently selected groups can be far more symmetric.

The theorem (a useful version)

Suppose X1,…,XnX_1,\ldots,X_n are independent and identically distributed with mean μ\mu and finite, positive variance σ2\sigma^2. Then, as nn grows,

Xˉn−μσ/n→ d N(0,1).\frac{\bar X_n-\mu}{\sigma/\sqrt{n}} \xrightarrow{\ d\ } N(0,1).

In words: the standardized sample mean approaches the standard normal distribution.

It does not say that the original population becomes normal. It does not promise that a sample size of 30 is always sufficient. And it does not automatically apply to distributions without finite variance or to observations with unsuitable dependence.

The required sample size depends, among other things, on how skewed or heavy-tailed the population is.

Two discoveries at once

The theorem gives us a shape: approximate normality of the standardized sample mean for sufficiently large samples.

And the standard error,

σn,\frac{\sigma}{\sqrt{n}},

tells us that the spread of sample means gets smaller with increasing sample size.

The mean of the sampling distribution remains at μ\mu. The estimates become more concentrated around it.

The sampling laboratory

Choose a population shape below, then choose a sample size. The laboratory will repeatedly draw samples and calculate a mean for each.

Start with a sample size of 1 and an exponential population. You should see a strongly skewed distribution. Change the size to 5, 20, and 80. The resulting distribution of sample means should get more bell-shaped and narrow.

Try the Bernoulli population next. With only two possible individual outcomes, how can averages produce so many possible values?

Every run is random, so the plots will differ. That is part of the point.

Check your understanding

  1. Does the central limit theorem claim that individual observations must become normally distributed?
  2. If the sample size increases by a factor of 9, what happens to the standard error under the standard assumptions?
  3. Why is the rule “30 observations is always enough” unreliable?
Suggested responses
  1. No: it describes the limiting distribution of a standardized average. 2. The standard error is divided by 3. 3. Rates of convergence depend on properties of the population, notably skewness and tails, among other assumptions.

The law of large numbers answers a different question

The weak law of large numbers says that Xˉn\bar X_n concentrates near μ\mu in probability under suitable conditions. With independent finite-variance observations, Chebyshev’s inequality gives P(∣Xˉn−μ∣≥ε)≤σ2/(nε2)P(|\bar X_n-\mu|\geq\varepsilon)\leq\sigma^2/(n\varepsilon^2). This bound tends to zero for any fixed positive tolerance. The CLT instead describes the shape of fluctuations after magnifying them by n\sqrt n.

For independent Bernoulli observations with p=0.2p=0.2 and n=100n=100, the mean of the sample proportion is 0.20.2 and its standard error is 0.2(0.8)/100=0.04\sqrt{0.2(0.8)/100}=0.04. The approximate probability that the proportion lies between 0.120.12 and 0.280.28 is the normal area between standardized endpoints −2-2 and 22, about 0.95450.9545. The actual sample proportion lives on the grid 0,0.01,…,10,0.01,\ldots,1; a binomial calculation and optional continuity correction can quantify the finite-sample difference.

Increasing the number of simulated repetitions smooths the laboratory’s displayed sampling histogram. Increasing the sample size changes the underlying sampling distribution itself. These are different controls. Ten thousand simulated samples of size one do not turn the sample-size-one distribution into a normal one.

Additional practice

  1. For variance 9 and sample size 36, find the standard error of a mean.
  2. State what Chebyshev gives for error at least 1 in this example.
  3. Why does a Cauchy population not satisfy the finite-variance CLT stated in this chapter?
Worked additional solutions
  1. 3/6=0.53/6=0.5.
  2. At most 9/(36⋅12)=0.259/(36\cdot1^2)=0.25. The bound is valid under its assumptions but can be loose.
  3. It has no finite variance or finite ordinary mean, so the theorem’s hypotheses fail. More data alone do not supply missing moments.

Open chapter with navigation, interactive labs, and R examples →

Unit 3

Statistical estimation and inference

Lesson 22 · Week 7

Confidence Intervals and the Meaning of 95 Percent

The parameter stays still. The intervals move.

Learning objectives:

  • Distinguish a point estimate from an interval-estimation procedure.
  • Explain the repeated-sampling meaning of confidence-interval coverage.
  • Calculate an idealized normal interval when the population standard deviation is known.

A newspaper says that a survey result is “accurate to within three percentage points, 95 percent of the time.” That sentence is trying to express uncertainty. Whether it does so accurately depends on how the survey was conducted and what the margin of error means.

Before dealing with complicated real-world surveys, we’ll use a simpler model where the mathematics is exact.

One estimate; many possible samples

Suppose a population has an unknown mean μ\mu. We draw a random sample of size nn and calculate the sample mean Xˉ\bar X.

That single number is a point estimate. If we drew another sample, we’d almost certainly get another number.

A confidence interval is constructed by a procedure designed to contain the fixed, unknown population parameter a specified proportion of the time over repeated samples.

The key distinction is between a random interval (before the data are collected) and a fixed parameter.

An idealized example

Suppose individual observations are independent and normally distributed with mean μ\mu and known population standard deviation σ=10\sigma=10.

Then the sample mean follows a normal distribution with standard error

SE(Xˉ)=10n.\mathrm{SE}(\bar X)=\frac{10}{\sqrt n}.

The exact 95 percent confidence interval for μ\mu is

Xˉ ± 1.959963984510n.\bar X\ \pm\ 1.9599639845\frac{10}{\sqrt n}.

If n=25n=25 and the observed sample mean is 52, this gives

52±1.9599639845(2)≈[48.08,55.92].52\pm1.9599639845(2)\approx[48.08,55.92].

If we ran the same sampling-and-interval procedure again and again under these assumptions, 95 percent of the resulting intervals would contain μ\mu.

For this idealized model, it is true even for small nn: normal observations and known σ\sigma give exact normal sampling behavior.

What 95 percent does not mean

Once the particular interval has been calculated, μ\mu is still a fixed parameter. In the frequentist interpretation, that interval either contains μ\mu or it doesn’t.

Saying that there is a 95 percent probability that this particular fixed interval contains this particular fixed parameter is not the usual frequentist interpretation. The 95 percent belongs to the coverage performance of the procedure.

Other frameworks, including Bayesian credible intervals, can assign probability to parameters under explicit probabilistic assumptions. They answer a different question.

Try the coverage experiment

The laboratory below makes the normally hidden repeated-sampling idea visible. It fixes μ=50\mu=50, draws fifty independent samples, and constructs a separate interval for each.

Change the sample size and nominal level; see how the interval width and misses change. Try repeated batches. Fifty intervals are not many, so the observed fraction may be 92 percent on one run and 98 percent on the next.

The confidence level describes the long-run behavior, not a guarantee about each short batch.

Important real-world caveats

The laboratory knows σ\sigma. Usually, we do not. For inference about a population mean with an unknown standard deviation under appropriate conditions, a Student-tt procedure is more typical. For proportions, specialized interval procedures avoid notorious weaknesses of the simplest normal approximation.

No confidence formula automatically repairs selection bias, dependence, bad measurement, or a mispecified model. Coverage claims depend on the data-generating process and the procedure.

Exercise

  1. With known σ=12\sigma=12, n=36n=36, and xˉ=100\bar x=100, give the approximate 95 percent interval.
  2. What changes across repeated confidence-interval experiments: the population mean or the endpoints?
  3. Does a 95 percent confidence procedure guarantee that exactly 95 of the first 100 intervals contain the parameter?
Worked answers
  1. The standard error is 12/36=212/\sqrt{36}=2; the margin is approximately 1.96(2)=3.921.96(2)=3.92, giving [96.08,103.92][96.08,103.92].

  2. The sample statistics and interval endpoints vary; the population mean is fixed.

  3. No. Coverage is a long-run property, and observed proportions fluctuate in finite collections.

Read further

See OpenStax: Confidence Intervals and the ASA GAISE guidance.

Derive coverage before interpreting one interval

In the independent normal known-σ\sigma model, Z=(Xˉ−μ)/(σ/n)Z=(\bar X-\mu)/(\sigma/\sqrt n) is standard normal. The statement P(−z≤Z≤z)=0.95P(-z\leq Z\leq z)=0.95, with z=z.975z=z_{.975}, can be rearranged as

P(Xˉ−zσ/n≤μ≤Xˉ+zσ/n)=0.95.P\left(\bar X-z\sigma/\sqrt n\leq\mu\leq\bar X+z\sigma/\sqrt n\right)=0.95.

Before sampling, the endpoints vary. The parameter does not. This derivation is the coverage guarantee for the procedure under its assumptions. After observing one interval, the event that it covers is either true or false, though unknown to us. A Bayesian interval can assign posterior probability under a specified prior and likelihood; it is a different construction, not an alternative verbal gloss for the same frequentist calculation.

For σ=12\sigma=12 and n=36n=36, the standard error is 2. An observed mean of 50 gives interval 50±1.959964(2)50\pm1.959964(2), approximately [46.0801,53.9199][46.0801,53.9199]. It concerns the mean, not 95% of individual observations. To plan margin of error at most EE under this model, solve n≥(zσ/E)2n\geq(z\sigma/E)^2 and round up. For E=3E=3, the result is n≥61.4656n\geq61.4656, so use at least 62 independent observations before allowing for missingness.

Further problems

  1. How does a 99% interval compare with a 95% interval from the same data and model?
  2. Why does quadrupling sample size halve this interval’s width?
  3. Explain why the laboratory’s 50 realized intervals need not contain exactly 48 successes at a nominal 95% level.
Worked further solutions
  1. The larger critical value gives a wider interval. Higher coverage requires a larger repeated-sampling acceptance region.
  2. Width is 2zσ/n2z\sigma/\sqrt n, so multiplying nn by four divides it by two.
  3. The number covering is random, with expectation 47.5 under exact calibration and independent repetitions. An expectation is not a required realized count.

Open chapter with navigation, interactive labs, and R examples →

Lesson 23 · Week 7

When Sigma Is Not Written on the Blackboard

Student t procedures for one population mean when the population spread is unknown.

Learning objectives:

  • Calculate a one-sample t interval and statistic.
  • Explain the degrees of freedom in a t procedure.
  • Evaluate independence and distribution assumptions.

The textbook’s normal-confidence-interval example gives us the population standard deviation. That is convenient and, outside a classroom exercise, rather suspicious.

In actual studies, the population does not generally hand us its unknown parameter, σ\sigma, with a helpful label. We estimate it from the sample. That extra uncertainty is why the t distribution matters.

Replace unknown sigma with sample information

For a sample of nn observations with mean xˉ\bar x and sample standard deviation ss, the estimated standard error of the mean is

SE⁡^(Xˉ)=sn.\widehat{\operatorname{SE}}(\bar X)=\frac{s}{\sqrt n}.

To test a hypothesized population mean μ0\mu_0, use

t=xˉ−μ0s/n.t=\frac{\bar x-\mu_0}{s/\sqrt n}.

For independent observations from a normal population, this statistic follows a Student t distribution with n−1n-1 degrees of freedom when the null is true. Compared with the standard normal distribution, the t distribution has heavier tails, especially when nn is small. As the degrees of freedom increase, it approaches the normal.

A numerical example

Five synthetic readings are 2, 4, 6, 8, and 10. Their mean is 6. Their sample standard deviation is 10≈3.1623\sqrt{10}\approx3.1623.

The estimated standard error is 10/5=2≈1.4142\sqrt{10/5}=\sqrt2\approx1.4142. Testing H0:μ=4H_0:\mu=4 yields

t=6−42≈1.4142t=\frac{6-4}{\sqrt2}\approx1.4142

with four degrees of freedom.

A two-sided 95% confidence interval is

xˉ±t.975,n−1sn.\bar x\pm t_{.975,n-1}\frac{s}{\sqrt n}.

Using t.975,4≈2.7764t_{.975,4}\approx2.7764, the interval is 6±3.92656\pm3.9265, approximately [2.07, 9.93]. It is wide because five observations cannot tell us very precisely where the population mean lies.

Why the design still matters

With small samples, the exact t reference distribution depends on the normal-population model. Outliers, extreme skew, dependence, and selection bias can make the nominal procedure inappropriate.

A larger sample can make a t procedure more robust to moderate nonnormality under appropriate conditions, but it does not turn a systematically biased sample into a representative one.

Reproduce it in R

x <- c(2, 4, 6, 8, 10)
t.test(x, mu = 4)

Read the estimate, interval, test statistic, degrees of freedom, and p-value as parts of one inferential argument. None is a replacement for the question you started with.

Check your understanding

  1. Why is the t critical value at n=5n=5 larger than the corresponding normal critical value?
  2. How many degrees of freedom does a one-sample t test have with 20 observations?
  3. Does a t test repair nonresponse bias?
Worked responses
  1. The population spread must be estimated from a small sample, adding uncertainty represented by heavier tails.

  2. Nineteen.

  3. No. An inferential formula does not correct a defective sample-selection mechanism.

Reference: R documentation for t.test.

Why the reference distribution has heavier tails

For independent normal observations, Z=(Xˉ−μ)/(σ/n)Z=(\bar X-\mu)/(\sigma/\sqrt n) is standard normal. The scaled sample variance U=(n−1)S2/σ2U=(n-1)S^2/\sigma^2 has a chi-square distribution with n−1n-1 degrees of freedom and is independent of ZZ. Their ratio Z/U/(n−1)Z/\sqrt{U/(n-1)} is the t statistic. A small denominator can produce unusually large ratios, accounting for the heavier tails. The independence and exact distribution claims here depend on the normal-population model; they are not consequences of merely computing a sample standard deviation.

The degrees-of-freedom count also has an algebraic explanation. Once the sample mean has been estimated, the centered deviations sum to zero. Specifying n−1n-1 of them determines the last. That constraint explains the variance denominator, while the normal model supplies the exact distributional theorem.

A two-sided test and its matching confidence interval invert the same inequality. Reject H0:μ=μ0H_0:\mu=\mu_0 at level α\alpha when ∣t∣>t1−α/2,n−1|t|>t_{1-\alpha/2,n-1}. Rearranging gives exactly the parameter values outside xˉ±t1−α/2,n−1s/n\bar x\pm t_{1-\alpha/2,n-1}s/\sqrt n. Thus zero inclusion and a two-sided test decision agree only when the procedures, assumptions, and confidence levels actually match.

Additional practice with solutions

  1. A synthetic sample has n=16n=16, mean 4242, and standard deviation 88. Find the standard error and statistic for H0:μ=38H_0:\mu=38.
  2. With t.975,15≈2.13145t_{.975,15}\approx2.13145, calculate a 95% interval.
  3. Would this interval establish that every individual measurement lies in its range?
  4. Explain why repeated readings on one instrument may not give sixteen independent observations.
Worked additional solutions
  1. SE=8/4=2SE=8/4=2 and t=(42−38)/2=2t=(42-38)/2=2, with 15 degrees of freedom.
  2. 42±2.13145(2)42\pm2.13145(2), approximately [37.7371,46.2629][37.7371,46.2629]. The value 38 lies inside, so the matching two-sided 5% test does not reject it.
  3. No. The interval concerns the population mean, not individual spread or prediction.
  4. Serial correlation or shared calibration error can connect readings. Their information content then differs from independent sampling; increasing the reading count alone does not remove shared error.

Open chapter with navigation, interactive labs, and R examples →

Lesson 24 · Week 7

A Poll's Margin of Error Is Not Magic

Estimating a proportion, Wilson intervals, and why coverage differs from representativeness.

Learning objectives:

  • Explain the binomial sampling model for an observed proportion.
  • Compute and interpret a Wilson interval.
  • Identify the weaknesses of the simple Wald interval.

A poll finds four supporters among twenty respondents. Our observed proportion is 4/20=.204/20=.20.

Can we conclude that twenty percent of the population supports the proposal? Only if the sample design permits that inference. And even then, twenty observations carry substantial random uncertainty.

The deceptively simple interval

A textbook may suggest the approximate interval

p^±1.96p^(1−p^)n.\hat p\pm1.96\sqrt{\frac{\hat p(1-\hat p)}{n}}.

This Wald interval is memorable and notoriously unreliable in small samples or when the true proportion lies near zero or one. In particular, if none of twenty trials succeeds, it returns [0,0][0,0]: a ludicrous assertion of certainty.

The Wilson score alternative

A commonly preferable approximate interval is the Wilson score interval. With z=1.96z=1.96, sample size nn, and observed proportion p^\hat p, define

c=p^+z2/(2n)1+z2/n,h=z1+z2/np^(1−p^)n+z24n2.c=\frac{\hat p+z^2/(2n)}{1+z^2/n}, \qquad h=\frac{z}{1+z^2/n} \sqrt{\frac{\hat p(1-\hat p)}{n}+\frac{z^2}{4n^2}}.

The interval is [c−h,c+h][c-h,c+h]. For four successes in twenty independent binomial trials, a 95% Wilson interval is approximately [0.081, 0.416].

Notice how wide that is. Twenty observations leave open a considerable range of possible population proportions.

At zero observed successes, Wilson still produces a positive upper bound instead of falsely declaring the event impossible.

The assumptions are not an optional footnote

A binomial proportion requires independent Bernoulli observations with a common success probability under the model. In a clustered or weighted survey, its variance will often require a design-based calculation.

No interval, Wilson or otherwise, can fix systematic response bias. If the twenty respondents were gathered outside a political rally, the method’s mathematical sophistication does not confer representativeness.

Reproduce it

R’s prop.test performs a score-based procedure with its own implementation details, including a continuity-correction option. Software procedures need to be identified precisely rather than indiscriminately called “the 95% interval.”

prop.test(4, 20, correct = FALSE)

Compare that answer with the Wilson calculation above.

Check your understanding

  1. Find the sample proportion for 18 successes in 50 trials.
  2. Why should a zero-success sample not necessarily have a zero-width interval?
  3. Does choosing a different interval estimator eliminate selection bias?
Worked responses
  1. 0.36.

  2. An unobserved event can still have a positive underlying probability.

  3. No. The sampling mechanism remains a distinct issue.

Further reading: R prop.test documentation.

Wilson’s interval comes from inverting a test

For an independent binomial sample with observed proportion p^=X/n\hat p=X/n, a score test of a candidate pp uses (p^−p)/p(1−p)/n(\hat p-p)/\sqrt{p(1-p)/n}. Retain candidate parameters satisfying

(p^−p)2≤z2p(1−p)/n.(\hat p-p)^2\leq z^2p(1-p)/n.

Multiplying out gives (n+z2)p2−(2np^+z2)p+np^2≤0(n+z^2)p^2-(2n\hat p+z^2)p+n\hat p^2\leq0. Solving this quadratic produces the Wilson endpoints already displayed. The denominator contains the candidate pp under the test, rather than replacing it immediately by p^\hat p. This inversion explains why Wilson avoids the zero-width failure of the Wald interval when all outcomes agree.

For zero successes in ten trials and z≈1.96z\approx1.96, Wilson’s lower endpoint is zero and its upper endpoint is z2/(10+z2)≈0.2775z^2/(10+z^2)\approx0.2775. The sample proportion is zero, yet a wide range of positive risks remains compatible with this small sample under the procedure. If every trial succeeds, symmetry gives a lower endpoint near 0.72250.7225 and upper endpoint one.

No nonrandomized binomial interval has exact nominal coverage at every parameter because its sample space is discrete. Wilson is generally better behaved than the elementary Wald interval, not universally exact. The Clopper–Pearson construction instead inverts binomial tail probabilities and is conservative in the usual coverage sense. Choose the method for its properties, and label it rather than simply calling every range a “95% interval.”

Additional practice

  1. Calculate the Wilson center for X=4X=4, n=20n=20, z=1.96z=1.96.
  2. Explain the Wald failure for X=0X=0.
  3. Does using Wilson repair biased recruitment?
Worked additional solutions
  1. (0.2+3.8416/40)/(1+3.8416/20)≈0.24834(0.2+3.8416/40)/(1+3.8416/20)\approx0.24834, shifted toward one-half compared with the raw proportion.
  2. Its estimated standard error p^(1−p^)/n\sqrt{\hat p(1-\hat p)/n} is zero, producing a misleading zero-width interval despite a finite sample.
  3. No. Interval calibration presumes an appropriate sampling model. It does not supply representativeness or independence absent from the design.

Open chapter with navigation, interactive labs, and R examples →

Lesson 25 · Week 8

Two Samples, Two Sources of Uncertainty

Comparing group means with Welch's method, and why design matters more than an impressive difference.

Learning objectives:

  • Distinguish independent groups from paired observations.
  • Calculate the standard error of the difference between two independent sample means.
  • Explain why Welch's t method allows different group variances and does not prove causality.

There are two ways to ask whether a difference is meaningful. We can ask whether two numbers are different. Or we can ask how plausible a difference of that magnitude would be under an appropriate model of uncertainty.

The first question is usually trivial. The second requires statistics.

Imagine comparing the results of two independent groups. One group has five observations, the other eight. Their sample means differ. Before celebrating, we ought to ask whether those means were estimated with comparable precision.

A pair of entirely fictional groups

Consider the following hypothetical scores:

  • Group A: 8,9,10,11,128,9,10,11,12
  • Group B: 3,4,5,6,7,8,9,183,4,5,6,7,8,9,18

A has a mean of 10; B has a mean of 7.5. The observed mean difference is 2.5 points.

But look at the observations. Group B is more variable, particularly because of its unusually large value of 18.

The sample variances are sA2=2.5s_A^2=2.5 and sB2=22s_B^2=22. Those values matter because the uncertainty associated with an estimated group mean depends on both sample size and variability.

Independent samples: uncertainty comes from both groups

For independent observations sampled appropriately from two populations, the estimated standard error of a difference between means is

SE^(XˉA−XˉB)=sA2nA+sB2nB.\widehat{\mathrm{SE}}(\bar X_A-\bar X_B) =\sqrt{\frac{s_A^2}{n_A}+\frac{s_B^2}{n_B}}.

In our fictional example this is

2.55+228=3.25≈1.803.\sqrt{\frac{2.5}{5}+\frac{22}{8}} =\sqrt{3.25}\approx1.803.

So our observed difference of 2.5 is only about 2.5/1.803≈1.392.5/1.803\approx1.39 estimated standard errors from zero.

This calculation does not establish whether the groups were selected appropriately. It simply describes uncertainty under a model.

Welch’s t test

A common procedure for independent means is Welch’s two-sample t test. Unlike the traditional pooled-variance Student t procedure, it does not assume the two populations have the same variance.

Its test statistic for a hypothesized zero mean difference is

t=XˉA−XˉBsA2/nA+sB2/nB.t=\frac{\bar X_A-\bar X_B}{\sqrt{s_A^2/n_A+s_B^2/n_B}}.

Welch’s method uses an approximate degrees-of-freedom calculation reflecting the two sample variances and group sizes.

In R, the default independent two-sample call is:

A <- c(8, 9, 10, 11, 12)
B <- c(3, 4, 5, 6, 7, 8, 9, 18)
t.test(A, B, paired = FALSE, var.equal = FALSE)

The output includes an estimated difference, t statistic, degrees of freedom, confidence interval, and p-value. Read all of them rather than treating the p-value as the research finding.

This procedure is not appropriate for every dataset. Tiny, heavily skewed samples or extreme observations can undermine the approximation, and dependence between observations changes the variance structure.

Wait—were the observations paired?

If we measured the same eight people before and after an intervention, those are paired observations. The useful quantities are the eight within-person differences, not two independent samples.

A paired t procedure is mathematically a one-sample t procedure applied to the paired differences. Pairing can remove between-person variability, but only when the pairing genuinely describes the study design.

Do not treat two measurements on the same people as independent simply because the software accepts two columns.

A statistical test is not experimental design

Even if a two-sample test reports a very small p-value, that does not prove the group difference was caused by a treatment. The groups might differ for other reasons.

For randomized experiments, assignment helps causal interpretation; for observational comparisons, confounding remains a concern.

Exercise

  1. Find the mean difference of the fictional groups above.
  2. Recalculate its estimated standard error using sA2=2.5s_A^2=2.5, nA=5n_A=5, sB2=22s_B^2=22, and nB=8n_B=8.
  3. Why would a paired test be inappropriate if Group A and Group B are entirely different people?
Suggested responses
  1. 10−7.5=2.510-7.5=2.5.

  2. 2.5/5+22/8=3.25≈1.803\sqrt{2.5/5+22/8}=\sqrt{3.25}\approx1.803.

  3. There are no meaningful within-person pairs. Pairing depends on study design, not a convenient arrangement of rows.

Read further

See the official R documentation for t.test for the distinction between paired and independent tests and Welch’s default variance treatment. The ASA GAISE teaching recommendations stress inference in the context of study design.

Completing the Welch calculation

A test name is not yet a reproducible analysis. With u=sA2/nAu=s_A^2/n_A and v=sB2/nBv=s_B^2/n_B, the Welch–Satterthwaite degrees of freedom are

ν=(u+v)2u2/(nA−1)+v2/(nB−1).\nu=\frac{(u+v)^2}{u^2/(n_A-1)+v^2/(n_B-1)}.

Here u=0.5u=0.5, v=2.75v=2.75, and ν=9.2421875\nu=9.2421875. Fractional degrees of freedom are intentional: this is an approximation matching the uncertainty in the estimated variance, not a count of people. With SE=3.25SE=\sqrt{3.25}, the statistic is t≈1.38675t\approx1.38675. The two-sided p-value is approximately 0.198050.19805, obtained from a t distribution with that degrees-of-freedom value. Under the model and a prespecified 5% threshold we would not reject equal means. This does not establish equality.

The approximate 95% interval for μA−μB\mu_A-\mu_B is

2.5±t.975,ν3.25≈2.5±2.253153(1.802776)=[−1.56193,6.56193].2.5\pm t_{.975,\nu}\sqrt{3.25} \approx2.5\pm2.253153(1.802776) =[-1.56193,6.56193].

The interval includes both a modest negative difference and a substantial positive one on the score scale. “No significant difference” suppresses that information. State the estimate and interval before the test decision, and explain how selection and outliers could limit the result. The t approximation does not guarantee 95% actual coverage for every pair of nonnormal populations.

The variance formula follows from independence: Var⁡(XˉA−XˉB)=σA2/nA+σB2/nB\operatorname{Var}(\bar X_A-\bar X_B)=\sigma_A^2/n_A+\sigma_B^2/n_B. With correlated group means an additional −2Cov⁡(XˉA,XˉB)-2\operatorname{Cov}(\bar X_A,\bar X_B) term appears. This is why pairing is a design fact with mathematical consequences. Equal sample sizes do not create independence, and unequal sizes do not destroy it.

Further problems

  1. Two independent groups have means 12 and 9, variances 16 and 9, and sample sizes 16 and 9. Calculate the estimated difference and standard error.
  2. If both sample sizes are multiplied by four with the same observed variances, how does that standard error change?
  3. Explain why the interval above does not imply a 95% probability that this fixed population difference lies inside these realized endpoints.
  4. What changes if the observations are before-and-after scores on the same people?
Worked further solutions
  1. Difference 33; estimated standard error 16/16+9/9=2\sqrt{16/16+9/9}=\sqrt2.
  2. Each variance contribution is quartered, so the standard error is halved. This assumes the same independence structure and does not address bias.
  3. In the frequentist model the parameter is fixed. The repeated-sampling interval procedure carries the approximate coverage statement; these observed endpoints no longer vary.
  4. Form within-person differences and analyze their mean. Their variance incorporates the covariance between before and after; applying an independent-groups formula discards that information.

Open chapter with navigation, interactive labs, and R examples →

Lesson 26 · Week 8

Before and After Is Not Two Independent Groups

Paired observations, change scores, matched designs, and paired t inference.

Learning objectives:

  • Recognize a paired design.
  • Use within-pair differences for inference.
  • Identify causal limitations of simple before-and-after studies.

Five people each take one assessment before training and another after training. We have ten scores. Do we have ten independent observations?

No. We have five people, each observed twice. That relationship is the important part of the data.

Subtract first, infer second

Suppose the fictional scores are:

Person Before After Change
A 60 64 4
B 65 70 5
C 70 71 1
D 75 81 6
E 80 85 5

The differences are [4,5,1,6,5][4,5,1,6,5], with mean 4.24.2. A paired t test is simply a one-sample t procedure on those five differences:

t=Dˉ−δ0sD/n,t=\frac{\bar D-\delta_0}{s_D/\sqrt n},

where δ0\delta_0 is the mean change hypothesized under the null.

The variability between people at baseline cancels from each individual’s difference. That can improve precision substantially.

Not everything can be paired

Two unrelated groups of five people cannot be made into matched pairs by sorting the data and placing the rows side by side. Pairing is a property of the design: repeated measures on the same unit, or legitimately matched units chosen under a specified method.

The differences also need their own assumptions. In a small paired t test, we care about the distribution of the differences, not separately about the distributions of before and after scores.

Causality is still hiding in the hallway

Even if every student improves, we cannot immediately attribute improvement to the training. Practice on the test, aging, concurrent instruction, or ordinary fluctuation could explain some of the change.

An appropriately randomized comparative design can support stronger attribution. A before-and-after contrast on its own mainly describes change.

In R

before <- c(60,65,70,75,80)
after  <- c(64,70,71,81,85)
t.test(after, before, paired = TRUE)

Compare this with a one-sample test on after - before; they are algebraically equivalent.

Check your understanding

  1. What is the observational unit and sample size in the paired analysis?
  2. What is the sample mean change?
  3. Why can a valid paired comparison still fail to identify a causal training effect?
Worked responses
  1. One person contributes one difference; n=5n=5.

  2. 4.2 points.

  3. Other changes through time may influence the results without a credible comparative design.

The covariance that pairing preserves

For paired measurements Ai,BiA_i,B_i, define Di=Bi−AiD_i=B_i-A_i. Then Var⁡(D)=Var⁡(B)+Var⁡(A)−2Cov⁡(A,B)\operatorname{Var}(D)=\operatorname{Var}(B)+\operatorname{Var}(A)-2\operatorname{Cov}(A,B). Positive within-person covariance can make differences much less variable than the raw measurements. Negative covariance can have the opposite effect. Pairing does not guarantee a smaller standard error; its justification is the actual matching structure.

For synthetic differences [4,5,1,6,5][4,5,1,6,5], the mean is 4.24.2. Squared deviations sum to 14.814.8, so sD2=14.8/4=3.7s_D^2=14.8/4=3.7 and SE=3.7/5≈0.86023SE=\sqrt{3.7/5}\approx0.86023. A 95% t interval with four degrees of freedom is

4.2±2.7764450.74≈[1.8116,6.5884].4.2\pm2.776445\sqrt{0.74}\approx[1.8116,6.5884].

The target is the mean within-pair change in the population represented by the pairs. The normality condition for an exact small-sample paired t procedure concerns the distribution of differences, not separate normality of before and after measurements. Missing one member of a pair removes that difference from a complete-pair analysis and can introduce selection bias if completeness depends on outcomes.

A before-and-after increase is still not a randomized treatment effect. Practice effects, time trends, regression to the mean, and cointerventions may explain change. A randomized comparison of changes can address a different question than testing change in one treated group alone.

Additional practice

  1. For differences [1,2,3,4][1,2,3,4], calculate their mean, sample variance, and estimated standard error.
  2. If all differences are zero, what happens to the usual t statistic for a zero null?
  3. Why must changing the direction of subtraction reverse the estimate and interval signs consistently?
Worked additional solutions
  1. Mean 2.52.5, squared deviations sum 55, variance 5/35/3, and standard error 5/12≈0.64550\sqrt{5/12}\approx0.64550.
  2. Both numerator and estimated standard error are zero; the displayed t ratio is undefined. Do not report a computed ratio or claim the finite sample proves a population equality.
  3. Replacing DD by −D-D changes the mean sign and preserves its standard error. An interval [L,U][L,U] becomes [−U,−L][-U,-L]; the estimand’s direction has changed.

Open chapter with navigation, interactive labs, and R examples →

Lesson 27 · Week 8

Two Rates, Two Denominators, One Question

Differences in proportions, pooled-null tests, and risk measures.

Learning objectives:

  • Interpret risk differences in percentage points.
  • Distinguish pooled-null and unpooled standard errors.
  • Recognize the limitations of normal approximations.

Suppose 18 of 30 people in Group A experience an outcome, compared with 12 of 30 in Group B.

The observed proportions are .60 and .40. The difference is 20 percentage points, not a 20 percent relative change.

Those distinctions matter enormously when communicating research.

An estimator, not yet an inference

For independent groups with sample sizes nA,nBn_A,n_B, define

Δ^=p^A−p^B.\hat\Delta=\hat p_A-\hat p_B.

An approximate unpooled standard error for the difference is

SE⁡^(Δ^)=p^A(1−p^A)nA+p^B(1−p^B)nB.\widehat{\operatorname{SE}}(\hat\Delta) =\sqrt{\frac{\hat p_A(1-\hat p_A)}{n_A}+ \frac{\hat p_B(1-\hat p_B)}{n_B}}.

Here that is .6(.4)/30+.4(.6)/30=.016≈.12649\sqrt{.6(.4)/30+.4(.6)/30}=\sqrt{.016}\approx .12649.

The naive unpooled 95% normal interval is approximately

.20±1.96(.12649)=[−.048,.448]..20\pm1.96(.12649)=[-.048,.448].

The interval includes zero. It also relies on approximations whose performance varies with sample size and underlying proportions.

Score-based or other better-calibrated intervals deserve consideration instead of treating this formula as the universal default.

Why some tests pool and intervals don’t

Under the null hypothesis H0:pA=pBH_0:p_A=p_B, the pooled proportion is

p^0=xA+xBnA+nB.\hat p_0=\frac{x_A+x_B}{n_A+n_B}.

For our example it is (18+12)/(30+30)=.5(18+12)/(30+30)=.5.

Using a shared estimate to evaluate a null of equality can make sense for certain score tests. It does not mean that an effect-size confidence interval should always use the same pooled standard error.

Risk difference, relative risk, and odds ratio

  • Risk difference: p^A−p^B=.20\hat p_A-\hat p_B=.20.
  • Risk ratio: p^A/p^B=1.5\hat p_A/\hat p_B=1.5.
  • Odds ratio: (.6/.4)/(.4/.6)=2.25(.6/.4)/(.4/.6)=2.25.

These are different mathematical measures. An odds ratio of 2.25 does not mean the event is 2.25 times as probable.

And none of them, by itself, establishes a causal effect of treatment. That interpretation depends on the design.

Check your understanding

  1. Find the risk difference and risk ratio for 12/20 versus 9/30.
  2. Why does a null-equality test sometimes use a pooled estimate?
  3. Why should a reported effect include both its units and uncertainty?
Worked responses
  1. Proportions .60 and .30, difference .30 and risk ratio 2.

  2. The null asserts a common probability across groups.

  3. Magnitude without context or sampling uncertainty can exaggerate the evidence.

Work through the entire comparison

Suppose two independent synthetic groups have 60 successes among 100 observations and 40 among 100. The estimated risk difference is Δ^=0.6−0.4=0.2\widehat\Delta=0.6-0.4=0.2. For a large-sample interval, an unpooled estimated standard error is

SECI=p^1(1−p^1)n1+p^2(1−p^2)n2=0.0048≈0.069282.SE_{CI}=\sqrt{\frac{\hat p_1(1-\hat p_1)}{n_1}+\frac{\hat p_2(1-\hat p_2)}{n_2}} =\sqrt{0.0048}\approx0.069282.

A normal 95% interval is approximately 0.2±1.96(0.069282)=[0.06421,0.33579]0.2\pm1.96(0.069282)=[0.06421,0.33579]. This is a large-sample Wald interval; small or extreme samples call for better-calibrated score-based or exact procedures. An interval formula that can exceed the parameter’s possible range should not be silently clipped and presented as having unchanged coverage.

For the equality null, the common proportion estimate is p^=(60+40)/200=0.5\hat p=(60+40)/200=0.5. The null standard error is p^(1−p^)(1/n1+1/n2)=0.005\sqrt{\hat p(1-\hat p)(1/n_1+1/n_2)}=\sqrt{0.005}. Thus z=0.2/0.005≈2.82843z=0.2/\sqrt{0.005}\approx2.82843, with a two-sided normal p-value about 0.004680.00468. The pooled test estimates variance under equality, whereas the unpooled interval estimates uncertainty without imposing equality. Software continuity corrections may yield a different displayed approximation; record the setting.

The same data give risk ratio 0.6/0.4=1.50.6/0.4=1.5 and odds ratio (0.6/0.4)/(0.4/0.6)=2.25(0.6/0.4)/(0.4/0.6)=2.25. Report the chosen effect scale and the event definition. Reversing “success” and “failure” reverses a risk difference and reciprocates an odds ratio, but does not generally reciprocate the risk ratio for the original event.

Additional practice

  1. Compare 30/50 with 20/50. Calculate the difference, risk ratio, odds ratio, and unpooled standard error.
  2. Why is this independent-groups formula inappropriate for the same people measured twice?
  3. If one group has no observed successes, does that prove its population risk is zero?
Worked additional solutions
  1. Rates remain 0.6,0.40.6,0.4, giving 0.20.2, 1.51.5, and 2.252.25. The standard error is 0.0096≈0.09798\sqrt{0.0096}\approx0.09798, larger because the group sizes are halved.
  2. Paired binary outcomes have dependence; the numbers changing in opposite directions carry the relevant information. Independent variance addition omits the covariance.
  3. No. Zero is a sample count. A suitable one-sided or two-sided interval still permits positive population risks, depending on the procedure and confidence level.

Open chapter with navigation, interactive labs, and R examples →

Lesson 28 · Week 9

Hypothesis Tests and P-Values

A p-value does not tell you the probability that your hypothesis is true.

Learning objectives:

  • Define a null and alternative hypothesis in a specific model.
  • Interpret a two-sided exact binomial p-value correctly.
  • Distinguish statistical significance, effect size, and practical importance.

Few numbers in science are more confidently misunderstood than the p-value. A paper reports p=.03p=.03; somebody announces that there is only a 3 percent chance the finding happened by chance, or a 97 percent chance the researcher’s hypothesis is correct.

Neither statement follows.

To understand what a p-value measures, we need a model, a question, and a way of deciding what results count as unusually far from the model’s expectation.

Begin with a claim

Suppose we suspect a coin might be unfair. We plan to toss it twenty times.

Our null hypothesis is

H0:p=.5,H_0:p=.5,

where pp is the coin’s probability of heads on independent tosses.

A two-sided alternative says

HA:p≠.5.H_A:p\neq.5.

We specify a test statistic: XX, the number of heads in twenty independent tosses.

Under the null hypothesis, XX has a binomial distribution with n=20n=20 and p=.5p=.5.

What counts as extreme?

Suppose we observe 18 heads. The null model expects an average of 10. Counts of 18, 19, and 20 are unusually high; counts of 2, 1, and 0 are equally far from the null expectation in the opposite direction.

A two-sided exact test sums their null probabilities:

P(X≤2 or X≥18∣H0)=2(1+20+190)220≈0.00040245.P(X\le2\text{ or }X\ge18\mid H_0) =\frac{2(1+20+190)}{2^{20}} \approx0.00040245.

That is the two-sided exact binomial p-value for 18 heads in 20 tosses, using this pre-specified measure of extremeness.

Under the fair-coin model and the planned test, results at least this extreme would be rare.

But this is not P(H0∣data)P(H_0\mid\text{data}). The null hypothesis was an assumption inside the probability calculation, not a random event to which we assigned a posterior probability.

Significance is not effect size

If a p-value is below a threshold such as .05.05, a conventional decision rule calls the result “statistically significant.” That threshold is a choice about evidence and error rates, not a universal boundary between true and false.

With a huge sample, an extremely small difference can yield a small p-value. With a tiny sample, a large difference might not cross the threshold. Statistical significance alone does not tell us whether an effect is important, consequential, or even measured without bias.

A sensible report includes context, estimated effects, uncertainty, the design, the assumptions, and what was decided before the data were analyzed.

Manipulate the evidence

The laboratory below shows exact probabilities under the fair-coin null. Change the number of tosses and the observed number of heads.

The gold bars represent outcomes at least as far from n/2n/2 as the observation; their probabilities sum to the displayed p-value.

Try 14 heads out of 20, then 18. The observation is farther from the null expectation in the second case, so the two-sided p-value is smaller.

Data snooping changes the rules

Suppose you repeatedly inspect results and stop collecting observations the instant the p-value falls below .05.05. The null distribution of your entire procedure is no longer the one assumed by a single pre-planned fixed-sample test.

Likewise, trying dozens of outcomes and only reporting the smallest p-value can make random variation look persuasive.

These problems have names—optional stopping and multiple testing—and solutions that require choosing or adjusting the analysis procedure appropriately.

Exercise

  1. Interpret p=.04p=.04 without assigning a probability to the truth of the null hypothesis.
  2. For a fair coin tossed ten times, is getting exactly five heads the strongest evidence against fairness?
  3. Why should a researcher distinguish a pre-specified analysis from a result selected after examining many alternatives?
Worked answers
  1. Under the null model and the chosen test, a result at least as extreme as the observed one has probability .04.

  2. No. Five is exactly the null expected count and produces a two-sided p-value of 1 under the distance-from-center definition.

  3. Selection and repeated examination can change false-positive rates and invalidate the nominal single-test calibration unless addressed in the method.

Read further

See OpenStax: Hypothesis Testing with One Sample and the ASA GAISE recommendations.

The tail criterion is part of the test

Under a binomial null X∼Binomial(n,p0)X\sim\mathrm{Binomial}(n,p_0), an upper-tail p-value is Pp0(X≥xobs)P_{p_0}(X\geq x_{obs}). A lower-tail value uses the opposite direction. A two-sided discrete test must specify what counts as at least as extreme. One common exact convention sums the null probabilities of all outcomes whose mass is no greater than that of the observation. It need not equal twice the smaller one-sided tail when the null distribution is asymmetric. The site’s fair-coin example is symmetric, which conceals this potential difference.

For n=10n=10, p0=0.5p_0=0.5, and eight observed successes, the upper-tail probability is (45+10+1)/1024=56/1024=0.0546875(45+10+1)/1024=56/1024=0.0546875. By symmetry, the matching two-sided tail probability is 112/1024=0.109375112/1024=0.109375. Choosing the direction after seeing eight successes and presenting the one-sided value as prespecified changes the procedure’s false-positive behavior.

A valid p-value is calibrated so that under its null P(p≤α)≤αP(p\leq\alpha)\leq\alpha; discreteness can make the inequality strict. It is not generally uniform for a discrete exact test. Optional stopping, outcome searching, and adaptive exclusions can destroy the claimed calibration if not accounted for. Report the tested model and the analysis choices that produced the statistic.

Further problems

  1. For ten fair tosses and ten heads, find the one-sided and symmetric two-sided p-values.
  2. Why does failing to reject not establish equivalence?
  3. Why is an effect estimate with an uncertainty interval needed even after a small p-value?
Worked further solutions
  1. 1/10241/1024 and 2/10242/1024, respectively.
  2. Low precision can make both equality and large differences compatible with the data. Equivalence requires a prespecified practically negligible range and a suitable test.
  3. A p-value does not report effect magnitude, direction on the scientific scale, or the plausible range under an estimation model.

Open chapter with navigation, interactive labs, and R examples →

Lesson 29 · Week 9

Is This Die Playing by the Rules?

Expected categorical counts, chi-square goodness-of-fit tests, and reference distributions.

Learning objectives:

  • Compute expected counts under a categorical null.
  • Calculate Pearson's goodness-of-fit statistic.
  • Check sampling and expected-count assumptions.

We roll a supposedly fair six-sided die 60 times and record counts of [15,5,10,10,10,10][15,5,10,10,10,10].

The counts are not all ten. Does this mean the die is crooked? If we have learned anything by now, it should be that random variation makes observed counts unequal even when the probabilities are equal.

Calculate the discrepancy

Under a fair independent-roll model each face has probability 1/61/6. The expected count per face is 60/6=1060/6=10.

Pearson’s goodness-of-fit statistic is

X2=∑i=1k(Oi−Ei)2Ei.X^2=\sum_{i=1}^{k}\frac{(O_i-E_i)^2}{E_i}.

The first two cells contribute (15−10)2/10=2.5(15-10)^2/10=2.5 and (5−10)2/10=2.5(5-10)^2/10=2.5. The rest contribute zero. Thus X2=5X^2=5.

With six categories and a fully specified null distribution, the conventional asymptotic reference is chi-square with k−1=5k-1=5 degrees of freedom.

We can then calculate an upper-tail p-value. The statistic itself is not a probability.

Assumptions govern the reference distribution

The observations need an appropriate independent categorical sampling model. The categories must be exhaustive and mutually exclusive.

If expected cell counts are very small, the chi-square approximation can perform poorly, and exact or simulation-based alternatives may be preferable.

If we estimate model parameters from the same counts, the degrees of freedom may change. Don’t simply subtract one without considering the fitted parameters.

A software check

observed <- c(15,5,10,10,10,10)
chisq.test(observed,p=rep(1/6,6))

Read the expected counts, statistic, degrees of freedom, and assumptions together.

Check your understanding

  1. Under five equally probable categories and 100 observations, what is the expected count per category?
  2. Why does X2=0X^2=0 not prove a distribution is exactly fair?
  3. Why can sparse expected cells undermine the chi-square approximation?
Worked responses
  1. Perfect agreement in one sample does not establish the population model.

  2. The continuous asymptotic reference may poorly approximate the discrete small-sample distribution.

From counts to a model-based decision

For the die example, the upper-tail reference probability is P(χ52≥5)≈0.41588P(\chi^2_5\geq5)\approx0.41588. At a prespecified 5% threshold, this is not evidence sufficient to reject the uniform probability model. It is not a 41.6% probability that the die is fair. The probability describes discrepancies under the null model, not posterior odds among possible dice.

The counts obey a constraint: once five category counts and the total are known, the sixth is determined. That explains the five degrees of freedom for six fully specified probabilities. If parameters are estimated from these same data, the familiar k−1−mk-1-m adjustment requires a regular fitted-model setting with mm effective estimated parameters; it is not an unconditional subtraction rule for arbitrary adaptive models or category choices.

A single cell’s contribution can identify where discrepancies arise, but the global p-value concerns the sum. In this example the first two faces contribute the entire statistic, 2.52.5 each. Investigating them after seeing the table is exploratory. A follow-up claim about a particular face needs an appropriately specified comparison, especially if all six are searched.

For sparse categories, one option is to simulate many independent multinomial samples under the prespecified null and compare their statistics with the observed statistic. In a Monte Carlo test, (b+1)/(B+1)(b+1)/(B+1), where bb simulated values are at least as extreme among BB draws, avoids reporting an impossible zero simulated p-value and has a randomized-rank justification under the null. Record the random seed, repetition count, and Monte Carlo uncertainty. Pool categories only when substantively defensible, not to manufacture significance.

Additional practice

  1. With observed counts [12,8][12,8] and equal null probabilities, find expected counts, the statistic, and degrees of freedom.
  2. Why is the rejection region in the upper tail even when some observed cells are below expectation?
  3. Can a large sample make a small departure statistically detectable but practically unimportant?
Worked additional solutions
  1. Expected counts are [10,10][10,10], giving X2=4/10+4/10=0.8X^2=4/10+4/10=0.8 and one degree of freedom.
  2. Squaring converts both upward and downward deviations into positive discrepancy contributions. Larger totals indicate poorer agreement.
  3. Yes. Report observed proportions and substantive departures along with the statistic and p-value.

Open chapter with navigation, interactive labs, and R examples →

Lesson 30 · Week 9

Two Categories Walk into a Contingency Table

Association between categorical variables, expected cell counts, and the independence test.

Learning objectives:

  • Compute expected counts in a contingency table.
  • Interpret Pearson's test of independence.
  • Avoid mistaking an association for a causal relationship.

Eighty fictional commuters report whether they drive or use a train, and whether they frequently arrive late.

Mode Late Not late Total
Car 18 22 40
Train 10 30 40
Total 28 52 80

The observed late rates are 45% for drivers and 25% for train riders. Are these variables associated?

What independence predicts

Under a model in which the row and column classifications are independent, the expected count in row ii, column jj is

Eij=(row totali)(column totalj)n.E_{ij}=\frac{(\text{row total}_i)(\text{column total}_j)}{n}.

For the car-and-late cell, the expected count is 40(28)/80=1440(28)/80=14. The other expected counts are 26, 14, and 26.

Pearson’s chi-square statistic sums squared observed-minus-expected differences divided by the corresponding expected counts. Here:

X2=16/14+16/26+16/14+16/26≈3.516.X^2=16/14+16/26+16/14+16/26\approx3.516.

For a 2×22\times2 table, the usual reference degrees of freedom are (2−1)(2−1)=1(2-1)(2-1)=1 under appropriate conditions.

Interpretation before ritual

If the test indicates an association, that does not establish that switching a commuter from car to train would reduce lateness. Route distance, schedules, weather, job flexibility, and other factors might differ between the groups.

If the same commuter appears repeatedly, the assumed independent observational units may also be wrong.

When expected counts are sparse, a different procedure, such as Fisher’s exact test for a suitable 2×22\times2 reference model, can be preferable.

Ask R the same question

tab <- matrix(c(18,10,22,30), nrow=2,
  dimnames=list(Mode=c("Car","Train"),
                Late=c("Yes","No")))
chisq.test(tab)
prop.table(tab,1)

The row proportions are usually much easier to interpret than a bare p-value.

Check your understanding

  1. What is the expected car-and-late count under independence?
  2. What is the usual degrees-of-freedom formula for an r×cr\times c table?
  3. Why doesn’t an association imply that one classification caused the other?
Worked responses
  1. (r−1)(c−1)(r-1)(c-1).

  2. Confounding and selection, among other causes, may create or distort the association.

Derive the expected table and its constraints

Under independence, P(R=i,C=j)=P(R=i)P(C=j)P(R=i,C=j)=P(R=i)P(C=j). Estimating the marginal probabilities by row and column proportions gives Eij=RiCj/nE_{ij}=R_iC_j/n. These expected counts preserve the observed row and column totals. For an rr by cc table with positive relevant margins, fitting the margins leaves (r−1)(c−1)(r-1)(c-1) independent directions of discrepancy, the usual asymptotic degrees of freedom.

For the synthetic table [[18,22],[10,30]][[18,22],[10,30]], row totals are 40 each, column totals 28 and 52, and expected counts are [[14,26],[14,26]][[14,26],[14,26]]. Pearson’s statistic is

X2=2(1614+1626)≈3.51648.X^2=2\left(\frac{16}{14}+\frac{16}{26}\right)\approx3.51648.

The uncorrected one-degree-of-freedom p-value is approximately 0.060760.06076. R’s default for a two-by-two table may apply Yates’s continuity correction, so specify correct=FALSE to reproduce this exact uncorrected calculation. Neither answer licenses hiding the correction choice.

A measure of association is Cramér’s V=X2/[nmin⁡(r−1,c−1)]V=\sqrt{X^2/[n\min(r-1,c-1)]}. Here V≈0.20966V\approx0.20966. The first-row event proportion is 18/40=0.4518/40=0.45 and the second is 10/40=0.2510/40=0.25, a risk difference of 0.200.20. Those directional, interpretable rates convey information that a nonnegative global statistic does not.

A contingency table of independent people is not interchangeable with paired measurements on the same people or clustered respondents. For sparse two-by-two tables, Fisher’s exact test conditions on margins and tests a corresponding odds-ratio null under its model. “Exact” refers to the finite reference calculation; it does not guarantee the data-collection design is appropriate.

Additional practice

  1. If a three-by-four table meets the test assumptions, how many degrees of freedom does the independence statistic use?
  2. Show that expected counts for each row sum back to its observed row total.
  3. Why would repeated visits by the same person undermine the ordinary independent-count reference?
Worked additional solutions
  1. (3−1)(4−1)=6(3-1)(4-1)=6.
  2. ∑jRiCj/n=Ri(∑jCj)/n=Ri\sum_jR_iC_j/n=R_i(\sum_jC_j)/n=R_i.
  3. Visits share person-level characteristics and are not independent units. The reference variance and effective information may differ from the naive count.

Open chapter with navigation, interactive labs, and R examples →

Lesson 31 · Week 10

Not Significant Does Not Mean No Effect

Type I and II errors, power, meaningful effects, and sample-size decisions.

Learning objectives:

  • Define Type I and Type II error relative to a stated decision rule.
  • Explain statistical power and its dependence on alternatives.
  • Separate practical effect size from statistical significance.

A study reports p=.21p=.21 and announces that the treatment has no effect. This is a familiar leap—and an unjustified one.

The study may have found too little evidence to reject the null hypothesis. It has not necessarily proved the effect is zero. Perhaps it was far too small to detect a useful difference.

Two ways a decision can be wrong

Suppose we specify a significance threshold α=.05\alpha=.05 before collecting data.

A Type I error is rejecting the null hypothesis when that hypothesis is true. Under the correctly calibrated test, the probability of this error is controlled at the chosen threshold.

A Type II error is failing to reject the null under a specified alternative when the null is false. Denote its probability by β\beta.

Statistical power is 1−β1-\beta: the probability that the planned procedure rejects the null when that particular alternative is true.

Power is not a single universal property of a dataset. It depends on the effect being considered, the test, sampling variability, sample size, significance threshold, and underlying assumptions.

What improves power?

Increasing sample size usually reduces standard errors in appropriate independent sampling models, making a fixed effect easier to distinguish from chance variation.

Using more precise measurements or a design that removes irrelevant between-person variation can also help.

Lowering the significance threshold from .05 to .01 tends to reduce false-positive rejection under the null—but usually reduces power for a fixed alternative, all else equal.

The trade-off belongs in the design discussion, not a post-hoc explanation of an inconvenient p-value.

Effect size has a scientific scale

A statistically detectable difference of .01 unit might be trivial or enormously consequential depending on the scientific context.

Report the original units and a meaningful range of consequences. Standardized effect measures such as Cohen’s dd can help compare scales but do not replace subject-matter interpretation.

A huge study may report a tiny p-value for a minuscule effect. A small study can fail to reject even when data are compatible with large positive and negative effects. Confidence intervals help show the range of effects still compatible with the observations under a model.

Plan rather than retrofit

Sample-size planning should identify an effect worth detecting, plausible variability, desired power, significance threshold, allocation ratio, missing data, and the analysis strategy.

Choosing the “minimum interesting effect” after seeing the result changes the question. Pretending to have planned something that was chosen afterward is worse.

Check your understanding

  1. What probability does power describe?
  2. Does p=.21p=.21 establish no difference between populations?
  3. Why can a very large study find a practically negligible difference to be statistically significant?
Worked responses
  1. The probability of rejecting the null for a particular specified alternative under the planned procedure.

  2. No. It indicates insufficient evidence to reject at common thresholds, not proof of zero effect.

  3. With enough precision, even a tiny nonzero deviation can be statistically detectable.

Read ASA GAISE recommendations for interpretation in context.

Calculate power for a specified alternative

Consider an idealized independent normal sample with known σ\sigma. Test H0:μ=μ0H_0:\mu=\mu_0 against a two-sided alternative using ∣Z∣>z1−α/2|Z|>z_{1-\alpha/2}, where Z=(Xˉ−μ0)/(σ/n)Z=(\bar X-\mu_0)/(\sigma/\sqrt n). Under a true alternative μ1\mu_1, ZZ is normal with unit variance and mean d=(μ1−μ0)n/σd=(\mu_1-\mu_0)\sqrt n/\sigma. Power is

1−Φ(z1−α/2−d)+Φ(−z1−α/2−d).1-\Phi(z_{1-\alpha/2}-d)+\Phi(-z_{1-\alpha/2}-d).

For d=2d=2 and a critical value approximately 1.961.96, power is about 0.5160.516. The same test can have high power for a large alternative and low power for a small one; attaching one power number without an alternative is incomplete.

For planning a two-sided mean test, a useful normal approximation is n≈[(z1−α/2+z1−β)σ/Δ]2n\approx[(z_{1-\alpha/2}+z_{1-\beta})\sigma/\Delta]^2, where Δ\Delta is the magnitude worth detecting. With σ=10\sigma=10, Δ=5\Delta=5, 5% significance, and 80% desired power, this gives about 31.431.4, so round up to 32 before allowing for attrition. This is approximate, assumes the known-spread model, and differs from a full t-based calculation.

Power calculated after observing an effect estimate does not add independent evidence to the corresponding p-value. Instead report an interval and examine whether it excludes scientifically meaningful effects. Demonstrating practical equivalence requires prespecified equivalence margins and a suitable procedure, not merely failing to reject an equality null.

Further problems

  1. Under the planning approximation, what happens to required sample size if the effect worth detecting is halved?
  2. What happens if the standard deviation doubles?
  3. Explain why a 5% Type I error rate is not the probability that a particular significant conclusion is false.
Worked further solutions
  1. It quadruples because sample size scales as 1/Δ21/\Delta^2.
  2. It quadruples because sample size scales as σ2\sigma^2.
  3. The error rate conditions on the null being true and describes repeated use of the procedure. The probability of a false conclusion after selection also depends on the mix of true and false hypotheses, power, and reporting practices.

Open chapter with navigation, interactive labs, and R examples →

Lesson 32 · Week 10

The Nineteen Tests Nobody Mentioned

Multiplicity, familywise errors, false discovery rates, and pre-specification.

Learning objectives:

  • Calculate a multiple-testing false-positive probability under independence.
  • Explain a Bonferroni familywise error adjustment.
  • Separate exploratory discoveries from confirmatory analyses.

Imagine running twenty independent significance tests, each at the 5% threshold, when all twenty null hypotheses are true.

The probability of avoiding a false rejection on one test is .95.95. The probability of avoiding one on all twenty is .9520.95^{20}, assuming independence. Therefore

P(at least one false rejection)=1−(.95)20≈.6415.P(\text{at least one false rejection})=1-(.95)^{20}\approx .6415.

Roughly 64%. This is why trying twenty models and reporting only the most exciting one changes the statistical argument.

The family is part of the study

What constitutes the group or family of tests depends on the substantive question and inferential goals. It may include multiple outcomes, subgroups, predictors, and model specifications.

If a researcher examines twenty outcomes, selectively reports the smallest p-value, and describes it as the result of one planned test, the nominal evidence is overstated.

Independence made the numerical example easy. Tests in a real analysis are often correlated, so the exact false-positive calculation may differ. The basic problem remains.

Bonferroni: a simple guardrail

To control the probability of at least one false rejection across mm hypotheses, Bonferroni compares each p-value to α/m\alpha/m.

With 20 tests and a familywise target of .05.05,

αindividual=.05/20=.0025.\alpha_\text{individual}=.05/20=.0025.

This can be conservative, but it works under very broad dependence conditions when the individual tests’ p-values are valid.

Other procedures, such as Benjamini–Hochberg, can target the false discovery rate, the expected fraction of false discoveries among rejected hypotheses under appropriate conditions. That is a different goal from controlling the chance of any false discovery.

Exploration is good. Pretending it was confirmation isn’t.

Looking for patterns can generate valuable hypotheses. But a pattern discovered because it looked unusually strong should not automatically be presented as independently confirmed.

Pre-registration, a separate validation dataset, clear description of the analysis history, and appropriate adjustments can help. Transparency is more important than a ritual of declaring a p-value significant.

Example

A single pre-planned test produces p=.03p=.03. Under a predeclared .05.05 rule, it rejects its null, subject to the assumptions.

The same p=.03p=.03 is discovered after trying twenty tests. It no longer meets a Bonferroni familywise threshold of .0025.0025. The data have not changed, but the procedure that selected the reported result has.

Check your understanding

  1. What Bonferroni threshold corresponds to ten tests and a familywise level of .05?
  2. Why does reporting only the smallest p-value from many tests distort its interpretation?
  3. Must all exploratory statistical work be abandoned?
Worked responses
  1. .005.005.

  2. Selection favors random extremes, invalidating a single-test reading if multiplicity is ignored.

  3. No. Exploration is essential; it should be labeled honestly, and confirmatory claims require suitable validation.

Two procedures with different error targets

Bonferroni follows from the union bound: P(∪iEi)≤∑iP(Ei)P(\cup_iE_i)\leq\sum_iP(E_i). If each true null has false-rejection probability at most α/m\alpha/m, the probability of any false rejection is at most α\alpha, without assuming independence. Strong dependence can make the bound conservative, but does not invalidate it when individual p-values are valid.

Holm’s step-down procedure sorts the p-values p(1)≤⋯≤p(m)p_{(1)}\leq\cdots\leq p_{(m)}. Compare the smallest with α/m\alpha/m, the next with α/(m−1)\alpha/(m-1), and so on, stopping at the first failure. It controls familywise error under broad dependence conditions and never rejects fewer hypotheses than ordinary Bonferroni on the same family.

Benjamini–Hochberg instead finds the largest kk with p(k)≤kq/mp_{(k)}\leq kq/m and rejects the first kk. Its usual false-discovery-rate guarantee holds under independence and certain positive-dependence conditions. It is not a universal arbitrary-dependence guarantee. If there are no rejections, define the false-discovery proportion as zero; FDR is its expectation, not the realized false fraction in every study.

For p-values [0.001,0.01,0.03,0.2][0.001,0.01,0.03,0.2] with target 0.050.05, Bonferroni rejects the first two because the common threshold is 0.01250.0125. Holm rejects the first two and stops at 0.03>0.0250.03>0.025. BH compares with [0.0125,0.025,0.0375,0.05][0.0125,0.025,0.0375,0.05], finds k=3k=3, and rejects the first three. The extra rejection reflects a different error criterion, not a calculation error.

Further problems

  1. Apply BH at q=0.05q=0.05 to [0.01,0.04,0.08][0.01,0.04,0.08].
  2. Explain why searching twenty outcomes but adjusting only the two reported ones conceals multiplicity.
  3. What must be stated when reporting an adjusted p-value?
Worked further solutions
  1. Thresholds are approximately 0.01667,0.03333,0.050.01667,0.03333,0.05. Only the first qualifies, so reject one.
  2. Selection occurred across all twenty; the adjustment must reflect the inferential family and selection procedure, not just the survivors.
  3. Name the procedure, family, target error rate, and relevant dependence assumptions, alongside effect estimates and uncertainty.

Open chapter with navigation, interactive labs, and R examples →

Lesson 33 · Week 11

Randomization Tests and the Logic of an Experiment

Sometimes we can calculate a p-value simply by rearranging the assignments.

Learning objectives:

  • State the sharp null hypothesis in a randomized experiment.
  • Explain why a randomization distribution depends on the assignment mechanism.
  • Calculate an exact two-sided randomization p-value for a small experiment.

Suppose we want to know if a new teaching technique improves test performance. One approach is to teach one class with the new technique, another with the old technique, and compare the averages.

That is not necessarily an experiment. If the two classes differ in their preparation, instructor, schedule, or anything else consequential, the comparison may tell us as much about the students as it does about the teaching.

We can improve matters by randomly assigning students to the teaching methods. Random assignment does not guarantee identical groups. Instead, it gives us a known mechanism by which the groups differ, allowing us to reason about which differences are surprising.

A deliberately tiny imaginary experiment

Imagine eight participants, randomly assigned so exactly four receive Treatment A and four receive Treatment B. The observed outcomes are:

  • A: 6, 7, 8, 9.
  • B: 2, 3, 4, 5.

Their sample means are 7.5 and 3.5, so the observed difference is

xˉA−xˉB=4.\bar{x}_A-\bar{x}_B=4.

Is that large? The answer depends on the question. We need to know what differences would be possible if the treatment had no effect and assignment were the only source of random variation.

The sharp null

A sharp null hypothesis states that each participant’s potential outcome would be unchanged by assignment to either treatment. Under this hypothesis, we can regard all eight observed values as fixed. The labels are what vary.

There are

(84)=70\binom84=70

ways to select four of the eight participants for A. If the actual assignment mechanism made all these allocations equally likely, each has probability 1/701/70.

We can enumerate the mean difference for every allocation. No central limit theorem or normal approximation is necessary.

For a two-sided alternative, we count assignments producing a difference at least as far from zero as the observed difference of 4. Only two allocations qualify: the four highest outcomes assigned to A, or the four lowest outcomes assigned to A.

Therefore the exact randomization p-value is

ptwo-sided=270≈0.02857.p_{\text{two-sided}}=\frac{2}{70}\approx0.02857.

For a pre-specified one-sided positive alternative, only the highest-to-A allocation qualifies, producing 1/70≈0.014291/70\approx0.01429.

The alternative must not be selected after looking at the outcome just because it gives a smaller p-value.

Experiment with all seventy assignments

The laboratory below shows the complete randomization distribution. Switch between the pre-specified two-sided and one-sided comparisons. The underlying results do not change; what counts as extreme does.

Every histogram bar represents the count of assignments yielding a particular mean difference. The accompanying table lists these counts exactly.

Assumptions matter more than arithmetic

This test’s special validity comes from the random assignment design. The p-value assumes that the allocation mechanism was really as described, and that the sharp null is being tested.

If Treatment A was preferentially given to participants with higher baseline performance, the labels would no longer be exchangeable under the same design. Simply rearranging them would not create a valid randomized experiment out of an observational dataset.

We also assume meaningful outcomes, an appropriate definition of the treatment, and no interference between participants under the simple potential-outcomes model. More complicated experiments require methods that respect their actual assignment designs.

Exercise

  1. Why are there 70 possible allocations rather than 256?
  2. What is the difference between a sharp null and a null statement only about the average treatment effect?
  3. If researchers observe the results and then choose the alternative that makes their p-value smallest, what is wrong with the nominal interpretation?
Worked responses
  1. We are choosing exactly four participants for group A, with the other four in B: (84)=70\binom84=70.

  2. A sharp null fixes every person’s outcome under either assignment and permits the entire randomization distribution to be calculated from the observed values. An average-effect null can hold even when individual effects are not all zero.

  3. Choosing the test after observing outcomes changes the analysis procedure and can invalidate the advertised error calibration.

Read further

The ASA GAISE recommendations emphasize technology-enabled investigative reasoning and study design. The OpenStax hypothesis testing chapter gives broader inferential context.

What is fixed and what is randomized

Under a sharp no-effect null, each participant’s outcome would be the same under either treatment. Their observed outcomes therefore stand in for both missing potential outcomes when enumerating the actual allowed assignments. For eight participants with exactly four assigned to A, there are (84)=70\binom84=70 equally likely allocations if that was the design. Outcomes are held fixed and labels are reassigned; this is not random sampling of a new population.

If the observed absolute mean difference is attained or exceeded in two assignments, the exact two-sided p-value is 2/70≈0.02857142/70\approx0.0285714. No plus-one correction is required when all assignments are enumerated and the observed one is already included. A Monte Carlo subset has different bookkeeping and simulation uncertainty. Ties should count as at least as extreme, consistently with the prespecified statistic.

Blocked randomization permits only assignments respecting the blocks. Cluster randomization moves whole clusters, not individual people. Enumerating all unrestricted individual relabelings in either case would calculate a reference distribution for an experiment that was not conducted. Exchangeability must come from the actual assignment or an explicitly defended model.

The sharp null differs from a zero-average-effect null: individual treatment effects could cancel in the average while remaining nonzero. An exact sharp-null test does not automatically provide an exact test for every weaker null. Its interpretation should retain the null that makes the outcome imputation possible.

Further problems

  1. How many allocations choose three treated participants among six?
  2. If exactly four of those allocations are at least as extreme, calculate the exact p-value.
  3. Why does random assignment among volunteers not establish representativeness of all residents?
Worked further solutions
  1. (63)=20\binom63=20.
  2. 4/20=0.24/20=0.2.
  3. Assignment supports a treatment comparison within the recruited group. Recruitment determines the relationship of that group to a broader population.

Open chapter with navigation, interactive labs, and R examples →

Lesson 34 · Week 11

Bootstrapping the Sampling Distribution

When a sample is all we have, resampling it reveals what the estimate might do.

Learning objectives:

  • Describe bootstrap sampling with replacement.
  • Distinguish a bootstrap distribution from the original data distribution.
  • Construct a basic percentile interval while identifying its limitations.

Suppose we want to estimate the average waiting time at a particular service desk. We have twelve observations, not twelve thousand. And one person had to wait much longer than everybody else.

We can calculate the mean. But how uncertain should we be about it?

Earlier we learned that sample statistics change from sample to sample. Ideally, we would repeatedly collect new samples from the entire population and study how our estimates vary. That isn’t usually practical.

The bootstrap offers a clever approximation: repeatedly create new samples from the data we already have.

A sample becomes our temporary population

Suppose our observed waiting times in minutes are:

4,  5,  6,  6,  7,  8,  9,  9,  11,  13,  18,  39.4,\;5,\;6,\;6,\;7,\;8,\;9,\;9,\;11,\;13,\;18,\;39.

Our sample contains twelve observations. A bootstrap replicate draws twelve values with replacement from those twelve, selecting each draw independently and giving each original observation equal probability.

With replacement means a value may appear multiple times in one replicate, while another value may not appear at all.

For each replicate, calculate the mean. Repeat perhaps 1,000 times. The resulting distribution of 1,000 means is the bootstrap distribution.

It gives us information about how the mean might vary under repeated samples from the empirical distribution, the distribution that puts probability 1/121/12 on each observed data point.

Why replacement matters

If we sampled twelve distinct positions without replacement from twelve original observations, every replicate would contain all twelve values. The mean would never vary.

We wouldn’t have learned anything about uncertainty.

Sampling with replacement introduces variation consistent with treating our observed dataset as a provisional stand-in for the population.

A bootstrap standard error

The standard deviation of the bootstrap means estimates the standard error of our original statistic. For suitable statistics and regularity conditions, the bootstrap can approximate sampling behavior without requiring us to work out a complicated formula for that statistic.

This is not magic. The bootstrap inherits the information—and the blind spots—of the original sample.

If our observations were selected badly, resampling the same biased dataset does not repair the bias.

Percentile intervals

A simple percentile bootstrap confidence interval uses quantiles of the bootstrap distribution.

For a nominal 95 percent interval, take the 2.5th and 97.5th percentiles of the bootstrap replicate estimates:

[q^0.025,q^0.975].[\widehat q_{0.025},\widehat q_{0.975}].

The lab below calculates a Monte Carlo approximation to these endpoints. Change the number of replicates and watch the endpoints fluctuate. Generating more bootstrap replicates reduces Monte Carlo noise; it does not create new information from the population.

This interval is easy to explain, but it is not universally well-calibrated. Small or skewed samples, bias, boundary parameters, dependence, and nonsmooth statistics can produce poor coverage. Studentized, bias-corrected, or otherwise tailored methods may be more appropriate.

The lesson is not that the percentile bootstrap replaces every confidence interval. It is that uncertainty can sometimes be approximated through carefully specified computational repetition.

Experiment

Look first at the original mean, then at the spread of the resampled means.

Notice that the exceptionally long wait of 39 minutes can be repeated several times—or not at all—in a bootstrap replicate. This affects the right tail of the bootstrap distribution.

Try 200 and then 3,000 replicates. The shape and endpoints will generally become more numerically stable with the larger count, although they will still vary.

Exercise

  1. Why do bootstrap samples have the same size as the original sample in this standard procedure?
  2. Why is sampling without replacement not useful for the mean in this example?
  3. Would creating a million bootstrap replicates make a convenience sample representative?
Worked responses
  1. We are approximating the distribution of the statistic at the original sample size under repeated sampling from the empirical distribution.

  2. A twelve-observation sample without replacement from the same twelve observations contains exactly the same values, and therefore the same mean.

  3. No. Additional replicates primarily improve the precision of the computational approximation, not the quality of the underlying evidence.

Read further

OpenStax Introductory Statistics 2e provides the conventional sampling-and-interval framework into which resampling methods fit. The ASA GAISE recommendations encourage computing to emphasize conceptual understanding.

What increasing bootstrap repetitions can and cannot do

For sample x1,…,xnx_1,\ldots,x_n, the empirical distribution places probability 1/n1/n at each observed record, counting repeated values with their multiplicity. A bootstrap sample draws nn times independently from that empirical distribution. More bootstrap repetitions reduce Monte Carlo error in summarizing this conditional distribution. They do not add original observations or make an unrepresentative sample representative.

For a mean, the empirical-distribution variance is vn=∑i(xi−xˉ)2/n=(n−1)s2/nv_n=\sum_i(x_i-\bar x)^2/n=(n-1)s^2/n. The exact conditional variance of a bootstrap sample mean is vn/n=(n−1)s2/n2v_n/n=(n-1)s^2/n^2. Thus the bootstrap’s plug-in standard error differs slightly from s/ns/\sqrt n in a tiny sample; this finite-sample effect is not a software bug.

For the sample [1,2,3][1,2,3], the original mean is 2 and sample variance is 1. The empirical variance is 2/32/3, so the exact bootstrap mean variance is 2/92/9 and its standard deviation 2/3≈0.471405\sqrt2/3\approx0.471405. The conventional estimated sampling standard error is 1/3≈0.577351/\sqrt3\approx0.57735. Enumerating all 33=273^3=27 ordered resamples can verify the conditional result without simulation noise.

Ordinary resampling of individual records assumes the observed units are suitably independent. For paired observations, resample pairs. For cluster samples, a design-respecting cluster bootstrap may be needed. Time series require dependence-aware methods. Percentile intervals also inherit estimator bias and skewness issues; an impressive number of repetitions does not solve them.

Further problems

  1. Why can an ordinary bootstrap sample contain repeated observations while omitting others?
  2. If only five original people were measured, how many original people have been studied after a million bootstrap repetitions?
  3. Why is the ordinary bootstrap poorly suited to learning about unseen extreme tails from a tiny sample?
Worked further solutions
  1. Sampling is with replacement from the empirical distribution; each draw can select any original record.
  2. Five. Resampling quantifies a conditional approximation, not new recruitment.
  3. The empirical distribution assigns no mass beyond observed values. It cannot invent tail information absent from the data without additional modeling assumptions.

Open chapter with navigation, interactive labs, and R examples →

Unit 4

Models, causal limits, and research practice

Lesson 35 · Week 12

Simpson's Paradox and the Missing Variable

How a published medical comparison reverses when we examine a third variable.

Learning objectives:

  • Compare pooled proportions with proportions calculated within groups.
  • Describe how different group compositions can reverse an association.
  • Explain why an observational comparison is not automatically causal evidence.

Here is a lovely little statistical nightmare: two treatment methods can show one ranking when we compare all patients, then the opposite ranking within every relevant group.

It is called Simpson’s paradox, though nothing in the arithmetic is actually contradictory. The trick is in what we have left out of the comparison.

A published historical example

In a 1986 British Medical Journal study, researchers compared historical outcomes of kidney-stone treatment methods. One method involved open surgery; another was percutaneous nephrolithotomy.

We will work with the recorded numerical outcomes as a statistical case study, not as clinical guidance. The procedures were compared across different periods and were not randomized into the same patient population.

First look only at the pooled data:

Method Successful cases Total Recorded success proportion
Open surgery (A) 273 350 78.0%
Percutaneous procedure (B) 289 350 82.6%

The pooled percentage is higher for B. If we stopped here, we might conclude that B had better outcomes in the comparison. But we would be leaving out an important variable: stone size.

Now split the data

The published counts can be separated by stone size:

Stone size A successful / total B successful / total
Smaller than 2 cm 81 / 87 = 93.1% 234 / 270 = 86.7%
At least 2 cm 192 / 263 = 73.0% 55 / 80 = 68.8%

Within each stone-size category, A has a higher recorded success proportion. How can that be true if B has the higher overall proportion?

Because the two methods were used for different mixtures of cases.

Of the 350 open-surgery observations, 263 involved larger stones. Of the 350 percutaneous observations, only 80 involved larger stones.

Larger-stone cases had lower success proportions under both procedures. The pooled comparisons are therefore weighted very differently.

Weighted averages can reverse an apparent relationship

For method A, the pooled observed success proportion is

873508187+263350192263=273350=.780.\frac{87}{350}\frac{81}{87}+\frac{263}{350}\frac{192}{263} =\frac{273}{350}=.780.

For B:

270350234270+803505580=289350≈.826.\frac{270}{350}\frac{234}{270}+\frac{80}{350}\frac{55}{80} =\frac{289}{350}\approx.826.

Each overall rate is a weighted average of the within-group rates. The weights are different for the two methods.

When the weights shift enough, the pooled ordering can reverse even though the within-group ordering stays the same.

Play with the comparison

Switch the laboratory from all stone sizes to each size category.

The data do not change. The denominator changes because we are asking a different question about the same dataset.

A single pooled percentage is sometimes a dangerously incomplete summary. Even a correctly calculated statistic can support a misleading story when a relevant variable is omitted.

Does this prove A was the better treatment?

No. These were observational historical comparisons of patients treated under different circumstances and periods. Stratifying by stone size identifies one important imbalance; it does not rule out all other differences, such as patient characteristics, clinician choices, practice changes, or severity within a size category.

Understanding Simpson’s paradox is therefore not a shortcut to causal inference. It is a reason to take study design, context, and multivariable thinking seriously.

The broad lesson extends far beyond medicine. Admissions rates, school achievement, transportation safety, and workplace metrics can all change meaning when we pool distinct groups.

Exercise

  1. What fraction of open-surgery cases involved larger stones? What fraction of percutaneous cases?
  2. Which method has the higher observed rate in each size group? Which has the higher pooled rate?
  3. Why does this dataset, by itself, not prove a causal treatment advantage?
Worked answers
  1. 263/350≈75.1%263/350\approx75.1\% of open-surgery cases and 80/350≈22.9%80/350\approx22.9\% of percutaneous cases involved larger stones.

  2. Open surgery has the higher recorded success proportion in both size groups, while the percutaneous method has the higher recorded pooled proportion.

  3. The procedures were not randomly assigned to otherwise comparable patients and were observed in different time periods; stone size is one relevant difference, not necessarily the only one.

Data provenance and further reading

The counts are historical results from Charig and colleagues, “Comparison of treatment of renal calculi by open surgery, percutaneous nephrolithotomy, and extracorporeal shockwave lithotripsy,” BMJ (1986), 292:879–882, doi:10.1136/bmj.292.6524.879.

See the Harvard Statistics explanation and a later review of Simpson’s paradox in clinical research. Only published aggregate counts are used; no patient-level records are distributed.

The arithmetic of aggregation

An aggregate success rate is a weighted average of stratum-specific rates: pA=∑swAspAsp_A=\sum_sw_{As}p_{As}, with weights equal to A’s stratum proportions. B generally has different weights wBsw_{Bs}. Consequently, even if pAs>pBsp_{As}>p_{Bs} within every stratum, the aggregate inequality need not hold. The comparison mixes within-stratum outcomes with different population compositions.

To isolate composition, a descriptive standardization can use common prespecified weights wsw_s and compare ∑swspAs\sum_sw_sp_{As} with ∑swspBs\sum_sw_sp_{Bs}. If A is better in every stratum, these common-weight averages preserve that direction. The result describes the chosen standardized population, whose weights must be explained. It is not automatically an estimate of a causal effect: treatment selection and unmeasured prognostic differences may remain within strata.

For a synthetic illustration, A has rates 0.9 and 0.6, B rates 0.8 and 0.5. With common half-and-half weights, standardized rates are 0.75 and 0.65. But if A’s easier-case share is 0.1 and B’s is 0.9, their observed mixture rates are 0.63 and 0.77, reversing the order. These synthetic numbers illustrate the mechanism separately from the cited historical dataset.

Further problems

  1. Recalculate the standardized comparison using weights 0.2 and 0.8.
  2. Why is the crude aggregate not arithmetically incorrect?
  3. Why might conditioning on the wrong variable introduce rather than remove bias?
Worked further solutions
  1. A is 0.2(0.9)+0.8(0.6)=0.660.2(0.9)+0.8(0.6)=0.66; B is 0.2(0.8)+0.8(0.5)=0.560.2(0.8)+0.8(0.5)=0.56.
  2. It correctly describes each group’s actual mixture. It answers a different descriptive question from a common-composition comparison.
  3. Conditioning on a mediator changes the effect target; conditioning on a common consequence can create an association. Adjustment requires a causal argument about the variable’s role, not a rule to include everything measured.

Open chapter with navigation, interactive labs, and R examples →

Lesson 36 · Week 12

Building a Line with Least Squares

A useful model of association, provided we remember what it can and cannot do.

Learning objectives:

  • Interpret slope and intercept in a simple linear regression.
  • Explain why ordinary least squares minimizes squared residuals.
  • Distinguish a descriptive regression fit from a causal claim.

Suppose you want to know whether a person’s hours of practice are related to how well they perform some task. You collect paired measurements and plot them.

A straight line looks plausible. Now what?

We need to decide which straight line best summarizes the relationship—and precisely what we mean by “best.”

The linear model

The familiar simple linear regression equation is

y^=b0+b1x.\widehat y=b_0+b_1x.

Here b0b_0 is the intercept, the predicted value when x=0x=0. The slope b1b_1 is the predicted change in yy associated with a one-unit increase in xx.

If the fitted line is y^=12+3x\widehat y=12+3x, moving from x=4x=4 to x=5x=5 changes the predicted yy from 24 to 27.

That does not prove that changing xx by one unit will cause yy to increase by three. Regression can describe observational associations without identifying causal effects.

Also, interpreting the intercept at x=0x=0 may be silly if the observed data only include xx values between 100 and 200.

What counts as a good line?

A residual is the difference between what we observed and what the line predicted:

ei=yi−y^i.e_i=y_i-\widehat y_i.

We could try to minimize the sum of residuals, but positive and negative residuals can cancel. Instead, ordinary least squares chooses the line minimizing the sum of their squares:

SSE⁡=∑i=1n(yi−b0−b1xi)2.\operatorname{SSE}=\sum_{i=1}^{n}(y_i-b_0-b_1x_i)^2.

For data in which the xx values are not all identical, the least-squares slope has the convenient formula

b1=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,b0=yˉ−b1xˉ.b_1=\frac{\sum_i(x_i-\bar x)(y_i-\bar y)} {\sum_i(x_i-\bar x)^2}, \qquad b_0=\bar y-b_1\bar x.

You needn’t calculate these by hand fifty times to understand the result. Instead, understand what the optimization rewards and penalizes.

Squaring deviations makes large errors particularly expensive. That can be a good property—but it also gives extreme observations considerable influence.

A fitted line isn’t a law of nature

Fitting a line requires relatively few mathematical assumptions. Inference about the slope, however, requires more care: how were observations collected, could outcomes be dependent, does variability change across predictor values, and is a linear mean function appropriate?

For descriptive prediction, we still need to check that the line doesn’t systematically miss an obvious curve. We should also be cautious about extrapolating beyond the range where observations were collected.

What about correlation?

For simple regression with an intercept, the estimated slope and Pearson correlation have the same sign. They are related by

b1=rsysx,b_1=r\frac{s_y}{s_x},

provided both sample standard deviations are positive.

But slope and correlation are not interchangeable. Correlation has no units; slope has units of yy per unit of xx. A relationship can be strongly linear while its slope is numerically very small, merely because the variables use different scales.

Exercise

  1. For (x,y)=(1,3),(2,5),(3,7)(x,y)=(1,3),(2,5),(3,7), find the fitted line.
  2. Why does ordinary least squares square residuals?
  3. Is the intercept always scientifically meaningful?
Worked responses
  1. Every point falls on y^=1+2x\widehat y=1+2x, so the sum of squared residuals is zero.

  2. Squaring avoids positive and negative cancellation and strongly penalizes larger errors. It also yields a mathematically convenient optimization problem.

  3. No. The value x=0x=0 might not be possible or might lie far outside the observed predictor range.

Read further

OpenStax: Linear Regression and Correlation introduces the same core ideas and applied questions.

Derive the normal equations

Minimize S(b0,b1)=∑i[yi−b0−b1xi]2S(b_0,b_1)=\sum_i[y_i-b_0-b_1x_i]^2. Setting its partial derivatives to zero gives ∑iei=0\sum_i e_i=0 and ∑ixiei=0\sum_i x_ie_i=0. The first implies b0=yˉ−b1xˉb_0=\bar y-b_1\bar x. Substitution into the second gives

b1=SxySxx,b0=yˉ−b1xˉ,b_1=\frac{S_{xy}}{S_{xx}},\qquad b_0=\bar y-b_1\bar x,

provided Sxx>0S_{xx}>0. The quadratic objective is minimized by these coefficients; if all predictors coincide, an intercept and slope cannot be separately identified.

For pairs [1,2,3,4,5][1,2,3,4,5] and responses [2,4,5,4,5][2,4,5,4,5], centered predictor squares sum to 10 and cross-products to 6. The fitted line is 2.2+0.6x2.2+0.6x, passes through (3,4)(3,4), and has residuals [−0.8,0.6,1,−0.6,−0.2][-0.8,0.6,1,-0.6,-0.2]. Their sum is zero and residual sum of squares is 2.4. The zero-sum property follows from the fitted intercept, not from a belief that individual errors cancel exactly in nature.

Least-squares fitting does not itself require normal errors. Normality, independence, and variance conditions enter particular inferential claims and prediction procedures. A deterministic algorithm can always return a line when the design is identified, even for data that make a straight-line scientific model inappropriate.

Further problems

  1. Fit a least-squares line to (0,1),(1,3),(2,5)(0,1),(1,3),(2,5).
  2. What changes if 10 is added to every response? If the predictor is converted from metres to centimetres?
  3. Why does the fitted line with an intercept pass through the observed mean pair?
Worked further solutions
  1. y^=1+2x\hat y=1+2x, with zero residual sum of squares.
  2. The intercept increases by 10 and slope stays fixed. Multiplying predictor values by 100 divides the numerical slope by 100, preserving fitted values.
  3. The normal equation gives b0=yˉ−b1xˉb_0=\bar y-b_1\bar x, so b0+b1xˉ=yˉb_0+b_1\bar x=\bar y.

Open chapter with navigation, interactive labs, and R examples →

Lesson 37 · Week 12

The Data the Regression Line Missed

Residual plots, nonlinear patterns, and the trouble with fitting the wrong model well.

Learning objectives:

  • Calculate and interpret a regression residual.
  • Recognize a curved residual pattern as evidence against a simple linear description.
  • Interpret R-squared without confusing fit, prediction, and causation.

A line can be mathematically optimal and still be the wrong description of the relationship.

Ordinary least squares will happily fit a line to observations arranged in a parabola. It will find the line that minimizes the squared vertical distances. The algorithm has done exactly what we asked.

The problem is that we asked the wrong question.

Look at the mistakes, not just the answers

For each observation, the residual is

ei=yi−y^i.e_i=y_i-\widehat y_i.

A positive residual means the observed value lies above its fitted value. A negative residual means it lies below.

Plotting residuals against the predictor, or against fitted values, can reveal things that a single regression coefficient conceals.

If a linear model describes the mean relationship reasonably well, residuals should not trace an obvious curve. Their spread and unusual points still need examination. Absence of an obvious pattern, however, is not proof that all model assumptions hold.

What does R-squared mean?

For a least-squares regression with an intercept, we can calculate

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2.R^2=1-\frac{\sum_i(y_i-\widehat y_i)^2}{\sum_i(y_i-\bar y)^2}.

The denominator is the total sum of squared deviations about the sample mean. The numerator is the remaining sum of squared residuals after fitting the line.

In this ordinary in-sample setting, R2R^2 summarizes the proportion of sample variation accounted for by the fitted model, on this sum-of-squares scale.

A value close to one means the fitted line accounts for much of the in-sample variability. It does not mean that the model is probably true, that a prediction will be equally accurate for new observations, or that xx causes yy.

There are important edge cases. When every observed yy is identical, the total sum of squares is zero and the usual fraction does not define R2R^2.

The curve hidden inside the line

The laboratory generates nine synthetic observations and fits a line. At first, the data are nearly linear.

As you increase the curvature, the relationship bends. The least-squares line adjusts, but it cannot reproduce the curve. The residuals begin to show a systematic pattern: observations are systematically above the line in some regions and below it elsewhere.

That is a clear visual warning that the linear form may be inadequate.

A better model might include a quadratic term or another scientifically appropriate functional form. But adding more terms simply to maximize R2R^2 can overfit noise. Model choice should use substantive knowledge, diagnostics, and honest out-of-sample evaluation.

Correlation and nonlinear dependence

Pearson correlation can be close to zero even when two variables have a strong curved relationship. Similarly, a fitted linear slope might be close to zero in symmetric curved data.

The sensible response isn’t to throw away statistics. It is to use the correct statistical question.

Exercise

  1. A line predicts 12, but the observed value is 17. What is the residual?
  2. Why might a U-shaped residual plot cast doubt on a straight-line mean model?
  3. Does R2=.9R^2=.9 imply a 90 percent probability that the model is correct?
Worked responses
  1. 17−12=517-12=5.

  2. A systematic U-shaped pattern indicates that the model systematically overpredicts or underpredicts across ranges of the predictor; it misses a curved relationship.

  3. No. R2R^2 is a descriptive ratio of sums of squares for the fitted sample, not a posterior probability or a causal claim.

Read further

See OpenStax’s regression chapter. For research-oriented analysis, residual diagnostics should also consider unequal variance, dependence, influential observations, and model stability.

A diagnostic sequence with distinct questions

A residual-versus-fitted plot examines whether the mean shape is appropriate and whether residual spread changes with fitted level. A residual-versus-time plot checks dependence or drift hidden by an unordered scatterplot. A normal quantile plot compares residual shape with a normal reference, relevant to exact small-sample inference. None is an automatic pass/fail certificate, particularly with a small sample.

Leverage measures how unusual a predictor configuration is. In simple regression with an intercept, hii=1/n+(xi−xˉ)2/Sxxh_{ii}=1/n+(x_i-\bar x)^2/S_{xx}. For the five-point example with xˉ=3\bar x=3, Sxx=10S_{xx}=10, endpoints at 1 and 5 have leverage 0.6, while the center at 3 has leverage 0.2. A large residual and high leverage together can make one observation influential. A high-leverage observation can also have a small fitted residual because it pulls the line toward itself.

With an intercept, the identity SST=SSreg+SSESS_T=SS_{reg}+SSE makes R2=1−SSE/SSTR^2=1-SSE/SS_T. Adding regressors cannot increase least-squares SSE on the same observed rows, so in-sample R2R^2 cannot decrease. This is not proof of better prediction. Compare held-out error, defensible model structure, and sensitivity, and keep the analysis sample fixed when attributing a change in fit to a predictor.

Further problems

  1. If SSE=20SSE=20 and SST=50SS_T=50, calculate R2R^2.
  2. What residual pattern suggests increasing variance?
  3. Why is automatic deletion of an influential observation not a diagnostic solution?
Worked further solutions
  1. 1−20/50=0.61-20/50=0.6.
  2. A fan-shaped spread increasing with fitted values or predictor level, subject to context and sample limitations.
  3. Influence may identify a legitimate important case, a model failure, or a recording error. Investigate provenance and report sensitivity; deleting it changes the evidence.

Open chapter with navigation, interactive labs, and R examples →

Lesson 38 · Week 12

A Regression Slope Needs a Standard Error

Sampling uncertainty, slope t tests, confidence intervals, and model diagnostics.

Learning objectives:

  • Calculate an estimated standard error for a simple regression slope.
  • Describe the slope t test in a model with independent errors.
  • Distinguish in-sample fit from warranted inference and prediction.

A regression program prints a slope of 0.6. Is that a strong association? It depends on what one unit of the predictor means, how spread out the observations are, and how uncertain the estimate is.

We should not stop at the fitted line.

Where the slope comes from

For nn paired observations, let

Sxx=∑i(xi−xˉ)2,b1=∑i(xi−xˉ)(yi−yˉ)Sxx.S_{xx}=\sum_i(x_i-\bar x)^2,\quad b_1=\frac{\sum_i(x_i-\bar x)(y_i-\bar y)}{S_{xx}}.

Once the intercept is fitted, the residual sum of squares is

SSE=∑i(yi−y^i)2.SSE=\sum_i(y_i-\widehat y_i)^2.

Under the usual independent constant-variance normal-error model, estimate the error variance as se2=SSE/(n−2)s_e^2=SSE/(n-2). The standard error of the slope is then

SE⁡^(b1)=se2Sxx.\widehat{\operatorname{SE}}(b_1)=\sqrt{\frac{s_e^2}{S_{xx}}}.

The n−2n-2 denominator reflects estimating both the intercept and slope.

A fully worked example

Consider five fictional paired observations:

x y
1 2
2 4
3 5
4 4
5 5

Here xˉ=3\bar x=3, yˉ=4\bar y=4, Sxx=10S_{xx}=10, and Sxy=6S_{xy}=6. The fitted line is

y^=2.2+0.6x.\widehat y=2.2+0.6x.

The residuals are [−.8,.6,1,−.6,−.2][-.8,.6,1,-.6,-.2], so SSE=2.4SSE=2.4. Thus se2=2.4/3=.8s_e^2=2.4/3=.8, and the slope standard error is .8/10≈.2828\sqrt{.8/10}\approx.2828.

For the null H0:β1=0H_0:\beta_1=0, the t statistic is 0.6/.2828≈2.1210.6/.2828\approx2.121, with three residual degrees of freedom under the stated model.

The sample is tiny; apparent positive slopes can still carry considerable uncertainty.

What else must be checked?

The usual test relies on a statistical model for observations and errors. Curvature, unequal residual variance, dependence, influential observations, or incorrect functional form can undermine a naive t reference distribution.

For multiple regression, slope coefficients also depend on which other predictors are included. Correlated predictors can increase uncertainty and complicate interpretation.

And none of this alone proves changing x causes y to change.

Reproduce with base R

fit <- lm(c(2,4,5,4,5) ~ c(1,2,3,4,5))
summary(fit)
confint(fit)

Report the coefficient in its original units, its uncertainty, design assumptions, and limitations.

Check your understanding

  1. Why is the residual degrees of freedom n−2n-2 in a simple intercept-plus-slope model?
  2. Does a high R2R^2 guarantee a significant causal slope?
  3. Why would extrapolation far beyond observed x values be risky?
Worked responses
  1. Two coefficients (intercept and slope) were estimated from the observations.

  2. No. Association, uncertainty, and causality are distinct claims.

  3. The fitted linear relationship may not hold outside the observed range.

An interval, a mean response, and a new observation

For the five-point example, SE(b1)=0.08≈0.282843SE(b_1)=\sqrt{0.08}\approx0.282843 and t.975,3≈3.182446t_{.975,3}\approx3.182446. A 95% slope interval is therefore

0.6±3.1824460.08≈[−0.30013,1.50013].0.6\pm3.182446\sqrt{0.08}\approx[-0.30013,1.50013].

The data show a positive fitted slope but also substantial uncertainty under the classical model. This interval refers to change in the conditional population mean response per unit of predictor, not a prediction interval for a new response.

At a specified predictor x0x_0, the estimated conditional mean is y^0=b0+b1x0\hat y_0=b_0+b_1x_0. Its standard error is se1/n+(x0−xˉ)2/Sxxs_e\sqrt{1/n+(x_0-\bar x)^2/S_{xx}}. For a new independent observation at that predictor, the prediction standard error is se1+1/n+(x0−xˉ)2/Sxxs_e\sqrt{1+1/n+(x_0-\bar x)^2/S_{xx}}. The extra one represents the new observation’s residual variability. Under the normal-error model, matching t critical values produce mean-response and prediction intervals, respectively.

At x0=3x_0=3 in the example, y^0=4\hat y_0=4, mean-response standard error 0.8/5=0.4\sqrt{0.8/5}=0.4, and new-observation standard error 0.8(1.2)≈0.97980\sqrt{0.8(1.2)}\approx0.97980. The resulting intervals are about [2.7270,5.2730][2.7270,5.2730] and [0.8818,7.1182][0.8818,7.1182]. Prediction is harder than estimating a conditional mean. Both intervals widen away from the observed predictor center, even before we confront the additional risk that the model ceases to hold outside its observed range.

These formulas treat predictor values as fixed or condition on them, assume correctly specified linear conditional means and independent constant-variance errors, and use normal errors for exact small-sample t calibration. Robust standard errors address some variance misspecification but do not repair nonlinear mean structure, selection, or confounding.

Additional practice

  1. Holding error variance and predictor spread per observation similar, why does increasing sample size tend to reduce slope uncertainty?
  2. Why is a prediction interval wider than a conditional-mean interval at the same input?
  3. If all predictor values are identical, which formula fails and what does that mean?
Worked additional solutions
  1. SxxS_{xx} generally grows with the number of independent observations, reducing se/Sxxs_e/\sqrt{S_{xx}}.
  2. A new observation has its own residual variability in addition to coefficient-estimation uncertainty.
  3. Sxx=0S_{xx}=0, so the slope is not identified. A flat predictor column supplies no observed variation with which to estimate a response trend.

Open chapter with navigation, interactive labs, and R examples →

Lesson 39 · Week 13

Three Means Enter, One F Statistic Leaves

One-way ANOVA, within-group and between-group variation, and post-hoc comparison.

Learning objectives:

  • Decompose total variability into between- and within-group sums of squares.
  • Calculate a simple one-way ANOVA F statistic.
  • State what rejecting a global equality null does and does not establish.

Two means? We can compare them. Three means? We could conduct three pairwise tests, but that invites the multiplicity problem and avoids a more fundamental question.

Do the groups show more separation than we’d expect from the variation within them?

That is the central question in a one-way analysis of variance, or ANOVA.

Separate two kinds of variation

Suppose fictional outcomes are

  • Group A: 2,3,42,3,4
  • Group B: 4,5,64,5,6
  • Group C: 6,7,86,7,8

The group means are 3, 5, and 7. The grand mean is 5.

The between-group sum of squares weights how far each group mean lies from the grand mean:

SSB=∑g=1Gng(xˉg−xˉ)2.SS_B=\sum_{g=1}^{G}n_g(\bar x_g-\bar x)^2.

Here each group has three observations, so SSB=3(4+0+4)=24SS_B=3(4+0+4)=24.

The within-group sum of squares adds the squared deviations of observations from their own group means:

SSW=∑g∑i∈g(xi−xˉg)2.SS_W=\sum_g\sum_{i\in g}(x_i-\bar x_g)^2.

Each group contributes 12+02+12=21^2+0^2+1^2=2, giving SSW=6SS_W=6.

Construct the F ratio

With three groups and nine total observations, the between-group degrees of freedom are G−1=2G-1=2 and within-group degrees of freedom are n−G=6n-G=6.

The mean squares are

MSB=24/2=12,MSW=6/6=1.MS_B=24/2=12,\qquad MS_W=6/6=1.

Therefore F=12/1=12F=12/1=12.

Under the classical normal independent-observation model with equal group variances and a null of equal group means, this statistic has an F reference distribution with 2 and 6 degrees of freedom.

What an omnibus rejection means

If the global equality hypothesis is rejected, we have evidence that not all population group means are equal under the model.

It does not automatically tell us exactly which pair differs. Planned contrasts or appropriately adjusted pairwise comparisons answer more specific questions.

Classical ANOVA assumes independent observations, an appropriate within-group error distribution, and equal variances. When spreads differ substantially, Welch’s ANOVA or another design-appropriate method may be preferable.

R demonstration

score <- c(2,3,4,4,5,6,6,7,8)
group <- factor(rep(c("A","B","C"), each=3))
summary(aov(score ~ group))

Then inspect group means and variance. Never use an F statistic as a substitute for understanding which participants entered each group.

Check your understanding

  1. Why isn’t F=12F=12 itself a probability?
  2. What does rejecting equal means across three groups establish?
  3. If observations are repeated on the same people, is independent one-way ANOVA automatically appropriate?
Worked responses
  1. It is a ratio of mean squares; the p-value is calculated from its reference distribution.

  2. Evidence that at least one population mean differs, not identification of every differing pair.

  3. No. Repeated measurements introduce dependence that requires a suitable design-aware method.

Prove the decomposition and complete the inference

Write each deviation as xig−xˉ=(xig−xˉg)+(xˉg−xˉ)x_{ig}-\bar x=(x_{ig}-\bar x_g)+(\bar x_g-\bar x). Squaring and summing makes the cross term vanish because ∑i(xig−xˉg)=0\sum_i(x_{ig}-\bar x_g)=0 within each group. Therefore SST=SSW+SSBSS_T=SS_W+SS_B. In the example, total squared deviation is 3030, partitioned into within-group 66 and between-group 2424.

The completed analysis table is:

Source Sum of squares Degrees of freedom Mean square F
Between groups 24 2 12 12
Within groups 6 6 1
Total 30 8

The upper-tail probability P(F2,6≥12)=0.008P(F_{2,6}\geq12)=0.008. Under the stated equal-variance independent normal-error model, a prespecified 5% omnibus test rejects equality of all three population means. The illustrative sample is tiny, so assumption assessment cannot be delegated to a reassuring software label. The observed group means and spreads must accompany the result.

The descriptive effect fraction η2=SSB/SST=24/30=0.8\eta^2=SS_B/SS_T=24/30=0.8 describes between-group separation in this sample. It is not evidence that group membership caused 80% of individual variation, and it can overestimate a population explained fraction in small samples. Adjusted measures and uncertainty require their own definitions.

A planned contrast asks a more specific question. For independent groups with common variance estimated by MSWMS_W, a contrast L=∑gcgxˉgL=\sum_gc_g\bar x_g, with ∑gcg=0\sum_gc_g=0, has estimated standard error MSW∑gcg2/ng\sqrt{MS_W\sum_gc_g^2/n_g}. Comparing C with A here gives L=4L=4 and SE=2/3≈0.81650SE=\sqrt{2/3}\approx0.81650. If many contrasts are selected or searched, the family of comparisons must be accounted for. An omnibus rejection does not identify them automatically.

Additional practice

  1. Show the total degrees of freedom equals the sum of the two component degrees of freedom.
  2. If every outcome is increased by 10, what happens to FF? If every outcome is multiplied by 2?
  3. Why does a global rejection not establish that every pair differs?
Worked additional solutions
  1. (G−1)+(n−G)=n−1(G-1)+(n-G)=n-1.
  2. Adding a constant leaves all centered deviations unchanged. Multiplying by two multiplies both sums of squares and both mean squares by four; their ratio remains the same.
  3. The null is a conjunction of all group-mean equalities. Its rejection establishes that at least one equality fails under the model, not which ones or how many.

Open chapter with navigation, interactive labs, and R examples →

Lesson 40 · Week 13

A Regression for Yes and No

Logistic models, probabilities, odds, coefficients, and responsible interpretation.

Learning objectives:

  • Explain why a linear probability model can be problematic.
  • Convert between log-odds, odds, and probability.
  • Interpret a logistic coefficient as a conditional odds ratio.

Suppose an outcome can only be yes or no. A straight-line regression might predict a probability of 1.4, or −.2. Neither is a probability.

Logistic regression avoids this particular embarrassment by modeling the log odds rather than probability directly.

Let p(x)p(x) be the modeled probability of an event given predictors. Logistic regression uses

log⁡(p(x)1−p(x))=β0+β1x.\log\left(\frac{p(x)}{1-p(x)}\right)=\beta_0+\beta_1x.

The inverse of the logit is the logistic function:

p(x)=11+e−(β0+β1x).p(x)=\frac{1}{1+e^{-(\beta_0+\beta_1x)}}.

Whatever real number appears on the right-hand side of the linear predictor, the resulting probability lies between zero and one.

Odds are not probability

Odds of 1:4 correspond to a probability of 1/(1+4)=.201/(1+4)=.20.

A logistic coefficient β1\beta_1 describes a one-unit change in log odds holding the other included predictors fixed. Exponentiating gives an odds ratio: eβ1e^{\beta_1}.

Suppose β0=−2\beta_0=-2 and β1=.5\beta_1=.5. At x=2x=2, the log odds are −1-1, so

p(2)=11+e1≈.269.p(2)=\frac{1}{1+e^1}\approx .269.

Increasing x by one multiplies fitted odds by e.5≈1.649e^{.5}\approx1.649 in this model. It does not multiply probability by 1.649; odds ratios and risk ratios are not the same.

A genuine R fit

Using a synthetic dataset of binary outcomes:

x <- c(0,0,1,1,2,2,3,3,4,4)
y <- c(0,0,0,1,0,1,1,0,1,1)
fit <- glm(y ~ x, family=binomial())
summary(fit)
predict(fit, newdata=data.frame(x=2), type="response")

Real models may require diagnostics, more predictors, assessment of dependence, and consideration of rare outcomes or separation.

Interpretation is conditional, not automatically causal

A predictor can be associated with the chance of an event without causing it. Study design and confounding remain central.

When communicating results, consider fitted probabilities or risk differences alongside odds ratios, and specify the population and predictors held fixed.

Check your understanding

  1. Convert odds of 1:3 into probability.
  2. What does eβ1e^{\beta_1} represent in a logistic regression?
  3. Does an odds ratio of 2 necessarily mean the event is twice as probable?
Worked responses
  1. 1/(1+3)=.251/(1+3)=.25.

  2. The model’s multiplicative change in odds per one-unit predictor increase, holding other terms fixed.

  3. No. Odds and probability are different scales.

Fitting requires a likelihood, not squared residuals

For independent binary responses yiy_i and modeled probabilities pip_i, the Bernoulli likelihood is ∏ipiyi(1−pi)1−yi\prod_i p_i^{y_i}(1-p_i)^{1-y_i}. Its log is

ℓ(β)=∑i[yiηi−log⁡(1+eηi)],ηi=β0+β1xi.\ell(\beta)=\sum_i\left[y_i\eta_i-\log(1+e^{\eta_i})\right],\qquad \eta_i=\beta_0+\beta_1x_i.

Logistic regression usually estimates coefficients by maximizing this expression numerically. The outcome model and optimization criterion differ from ordinary least squares. Replacing binary outcomes by logits is not a valid shortcut, because observed zeros and ones have infinite logits.

For the hypothetical coefficients −2-2 and 0.50.5, the probabilities at x=2x=2 and x=3x=3 are approximately 0.268940.26894 and 0.377540.37754. Their difference is about 0.108600.10860 while their odds ratio is e0.5≈1.64872e^{0.5}\approx1.64872. At x=0x=0 and 11, the same odds ratio corresponds to probabilities about 0.119200.11920 and 0.182430.18243, a smaller difference of 0.063220.06322. A constant log-odds slope does not imply a constant probability difference. Differentiating the logistic function gives dp/dx=β1p(1−p)dp/dx=\beta_1p(1-p), which makes the baseline dependence explicit.

If a coefficient estimate is bb with estimated standard error sbs_b, a large-sample Wald interval for its conditional odds ratio is [eb−zsb,eb+zsb][e^{b-zs_b},e^{b+zs_b}]. For b=0.5b=0.5, sb=0.2s_b=0.2, and z=1.96z=1.96, it is approximately [1.114,2.440][1.114,2.440]. This is an asymptotic interval, not an exact small-sample guarantee. Profile-likelihood methods can behave differently.

Complete separation occurs when a predictor boundary perfectly distinguishes all observed outcomes. Coefficients can diverge while the likelihood approaches a limiting supremum. A convergence warning or huge standard error should prompt inspection of the data and model, not automatic deletion of an inconvenient observation. Also inspect calibration, influential observations, and whether the logit relationship is plausibly linear in continuous predictors.

Additional practice

  1. Convert probability 0.80.8 to odds and log odds.
  2. If baseline probability is 0.20.2 and odds double, find the new probability.
  3. Why does a conditional odds ratio not automatically describe a causal intervention?
Worked additional solutions
  1. Odds 44 and log odds log⁡4≈1.38629\log4\approx1.38629.
  2. Baseline odds are 0.250.25; doubled odds are 0.50.5, giving probability 0.5/1.5=1/30.5/1.5=1/3.
  3. The coefficient conditions on included predictors under a model. Unmeasured confounding, selection, and the distinction between observing and intervening remain.

Open chapter with navigation, interactive labs, and R examples →

Lesson 41 · Week 13

Association, Confounding, and Causal Claims

Why knowing how observations were produced is more important than a small p-value.

Learning objectives:

  • Distinguish observational studies from randomized experiments.
  • Explain confounding and the role of a study's assignment mechanism.
  • State the limits of causal interpretation from correlations and stratified rates.

Suppose people who spend more time exercising tend to live longer. Should everyone exercise? That’s a plausible public-health recommendation, but the association itself is not enough to establish the size of exercise’s causal effect.

People who exercise may differ from people who do not in age, existing health, socioeconomic conditions, diet, access to care, and countless other ways. Those differences complicate the leap from association to cause.

Statistics can identify relationships. Causal inference asks what would happen if we actually intervened.

The counterfactual question

For a treatment TT with two levels, imagine that every person has two potential outcomes: Y(1)Y(1) if treated and Y(0)Y(0) if untreated.

An individual causal effect is

Y(1)−Y(0).Y(1)-Y(0).

The challenge is immediate: we generally observe only one of these outcomes for the same person under the same circumstances.

This is sometimes called the fundamental problem of causal inference. The missing counterfactual is not a software bug we can patch by collecting another variable.

Instead, we use research designs and assumptions to make comparisons informative.

Why random assignment matters

In a randomized experiment, treatment assignment is governed by a known random mechanism rather than participant choice or investigator preference.

That doesn’t guarantee equal measured characteristics in a particular small sample. What it does is remove systematic selection into treatment in expectation and provide a principled basis for estimating uncertainty from the assignment mechanism.

Randomization is not the same thing as random sampling:

  • Random sampling helps generalize appropriately from a sample to a population.
  • Random assignment helps identify treatment effects within the study by reducing systematic baseline differences between treatment groups.

An experiment can have randomized assignment among volunteers while those volunteers are not representative of the broader population.

Confounding: the third-variable problem

A confounder is a variable that complicates causal comparison because it is associated with treatment choice and relevant to the outcome, in a way that can create or distort the observed association.

Suppose one hospital uses a particular treatment mainly for difficult cases, while another treatment is used mostly for mild cases. Pooled treatment success rates are not comparing similar patient mixes.

In our Simpson’s paradox example, stone size changes the way the observed treatment rates compare when the data are stratified.

But stratification itself doesn’t prove which method causes better outcomes. Other relevant variables could still differ. The historical data were not a randomized head-to-head trial.

Statistical adjustment helps, but cannot conjure missing evidence

Methods such as regression adjustment, stratification, matching, and weighting can improve observational comparisons under appropriate assumptions.

They cannot automatically remove the influence of unmeasured confounders. Adjustment for variables measured after treatment can even introduce new biases. A sophisticated model is not a substitute for understanding the causal question and how the data arose.

When planning research, ask: What exactly is the intervention, who receives it, how are groups formed, what outcomes are measured, and which conclusions will the design support?

Communicating results responsibly

A good causal claim should say more than “the p-value was significant.” It should explain the population, design, comparison, outcome, effect estimate, uncertainty, and most important limitations.

A cautious result is not a weak result. Sometimes the most useful answer is that the available evidence does not identify the causal effect we hoped to measure.

Exercise

  1. Explain the distinction between random sampling and random assignment.
  2. Why might controlling for observed stone size fail to establish causation in the historical treatment comparison?
  3. What additional design information would you want before interpreting a study’s regression slope causally?
Worked responses
  1. Sampling is about selection from a target population; assignment is about how interventions are distributed among participants.

  2. Treatment groups could differ in other observed or unobserved characteristics and time periods, even within size strata.

  3. How treatment or exposure was chosen; possible confounding, temporal order, measurement validity, potential interference, sample selection, and the population to which conclusions would apply.

Read further

The ASA GAISE recommendations call for statistical thinking that integrates data context, ethical practice, and well-scoped communication. For broader introductory inference and applications, see OpenStax Introductory Statistics 2e.

Define the effect before selecting a regression

For person ii, let Yi(1)Y_i(1) and Yi(0)Y_i(0) be outcomes under treatment and control. Their individual causal effect is Yi(1)−Yi(0)Y_i(1)-Y_i(0), but ordinarily only one potential outcome is observed. The sample average treatment effect averages those unobserved differences over recruited people; a population effect averages over a specified target population. They need not coincide.

Random assignment makes treatment independent of potential outcomes under the design, allowing unbiased comparisons in expectation for suitable estimators and assignment schemes. It does not guarantee exact balance in the realized experiment. A causal interpretation also needs a sufficiently defined treatment and assumptions about interference: one person’s assignment must not silently alter another’s outcome in a model that assumes independent treatment exposure.

For observational adjustment, a common identifying assumption is conditional exchangeability: within measured covariates X, treatment assignment is unrelated to potential outcomes. Positivity requires both treatment possibilities to occur with positive probability in the covariate groups relevant to the target. Consistency connects the observed outcome to the potential outcome for the treatment actually received. These assumptions are stronger than a regression’s ability to produce coefficients and cannot all be checked from the observed association table.

Further problems

  1. Explain why comparing volunteers who choose treatment with those who decline leaves a counterfactual problem.
  2. What would positivity failure look like if every person in one age group received treatment?
  3. Distinguish a variable measured before treatment from an outcome caused by treatment when considering adjustment.
Worked further solutions
  1. The groups may differ in what their outcomes would have been even under the same treatment. Only one outcome per person is observed.
  2. There are no untreated comparisons in that group; the data cannot directly identify its untreated outcome distribution without extrapolation or additional assumptions.
  3. A pretreatment confounder may help make comparisons exchangeable. A post-treatment mediator lies on a causal pathway; adjusting for it can remove part of the total effect or create other bias.

Open chapter with navigation, interactive labs, and R examples →

Lesson 42 · Week 13

The Observations That Aren't There

Missing data, changing denominators, and why a data audit belongs before every model.

Learning objectives:

  • Count missing observations and identify which analyses exclude them.
  • Distinguish complete-case analysis from a full-data analysis.
  • Explain why unobserved values can undermine a naive estimate or regression.

The data in a spreadsheet can look reassuringly official. Rows, columns, units, tidy headings. Even the occasional blank cell seems manageable. Surely a computer can just ignore a few missing values.

It can. Whether it should is a much more interesting question.

A real dataset, not a textbook invention

R distributes a dataset named airquality, comprising daily environmental measurements in New York from May through September 1973.

The R documentation describes 153 daily records and six variables: ozone, solar radiation, wind, temperature, month, and day.

The ozone readings were recorded at Roosevelt Island; meteorological observations came from Central Park and LaGuardia Airport. The observations did not all come from a single instrument or location, an important detail before we interpret their relationships.

The dataset includes 37 missing ozone readings and seven missing solar-radiation readings. Temperature and wind are recorded for all 153 days.

These missing cells are not merely nuisance characters for a spreadsheet. They are part of the evidence we have.

Audit the data before analyzing it

In R, the first step is remarkably simple:

data("airquality", package = "datasets")
dim(airquality)
colSums(is.na(airquality))

This tells us the dataset’s shape and the missing-value count for every variable.

Now consider two different analyses:

mean(airquality$Temp)
mean(airquality$Ozone, na.rm = TRUE)

The temperature mean uses 153 observations. The ozone mean, after removing missing values, uses 116. They do not summarize the same number of days.

R’s mean() on a vector containing NA returns NA unless we specify how missingness should be handled. That’s inconvenient, but scientifically useful: it prevents a silent assumption.

The denominator changes inside regression, too

Suppose we fit a linear model describing ozone concentration in relation to solar radiation, wind, and temperature:

model <- lm(Ozone ~ Solar.R + Wind + Temp, data = airquality)
nrow(airquality)
nobs(model)

A complete-case regression uses only rows where all variables in the model are present. For this particular dataset and model, 111 observations remain.

So an analysis that began with 153 days uses only 111 for its regression. The other 42 rows did not contribute to the fitted coefficients. We should report that explicitly.

The total number of rows removed is not necessarily 37 + 7: some rows can be missing both ozone and solar radiation.

Three different missingness questions

Statistics distinguishes several mechanisms:

  • Missing completely at random (MCAR): missingness is unrelated to observed or unobserved data under the model.
  • Missing at random (MAR): after conditioning on appropriate observed information, missingness does not additionally depend on the unobserved values.
  • Missing not at random (MNAR): missingness depends on unobserved information even after conditioning as specified.

The phrase missing at random is unfortunately named. It does not mean that rows disappeared through a magical coin toss. It names a particular conditional statistical assumption.

We usually cannot determine the true missingness mechanism merely by inspecting the observed dataset. Subject-matter expertise, data-collection documentation, and sensitivity analyses matter.

A complete-case analysis may be reasonable under some assumptions. Under others, it can produce biased estimates or poorly represent particular conditions or dates.

A reproducible audit

Open the R Workbench from this lesson. The accompanying script counts missing values, compares denominators, identifies the rows used by the regression, and plots observed temperatures against ozone for records where both are available.

Do not interpret the fitted regression as demonstrating that temperature or wind caused ozone readings. The variables are observational, measurements came from different locations and times, and seasonality or other variables could affect the relationship.

Exercise

  1. How many nonmissing ozone observations appear in the 153-row dataset?
  2. Does a regression with 111 complete cases necessarily tell us why the other 42 rows are missing?
  3. If missing ozone readings disproportionately occurred on high-ozone days, what might happen to the observed-case average?
Suggested responses
  1. 153−37=116153-37=116.

  2. No. A complete-case model simply excludes those rows; understanding why data are absent requires additional investigation.

  3. The observed-case average could underestimate the all-day mean. That conclusion depends on the mechanism, and the missing ozone values themselves are not observed.

Provenance and data access

Source: R Core’s official documentation for datasets::airquality, citing New York State Department of Conservation and National Weather Service data, and Chambers, Cleveland, Kleiner, and Tukey, Graphical Methods for Data Analysis (1983).

We use the dataset as distributed with R and do not redistribute a copy here. It is historical, not a description of current New York air quality.

A sensitivity analysis that changes the unseen values

Consider a synthetic survey of 100 selected people. Eighty respond, with 48 supporters; 20 do not respond. Respondent support is 60%. Without assumptions about nonrespondents, population support among the 100 selected people could range from 48/100=0.4848/100=0.48 if none of the missing people support the proposal to 68/100=0.6868/100=0.68 if all do. This is an identification bound, not a confidence interval: it describes what missing outcomes alone permit before sampling uncertainty.

A simple sensitivity parameter assigns nonrespondents support probability qq. The full-group expected support becomes (48+20q)/100=0.48+0.2q(48+20q)/100=0.48+0.2q. Matching respondent support sets q=0.6q=0.6 and returns 0.60. Choosing q=0.2q=0.2 gives 0.52; choosing 0.9 gives 0.66. The observed responses cannot choose among these assumptions by themselves.

Missing at random is conditional: after conditioning on the included observed information, missingness does not additionally depend on the unseen value under that model. It is not a claim that every person has an equal response probability. Multiple imputation generally propagates uncertainty across plausible completed datasets; filling every missing value with a single mean instead treats invented values as known and often understates uncertainty and distorts associations.

Further problems

  1. A sample has 30 observed successes, 50 observed failures, and 20 unknown outcomes. Find worst-case bounds on its complete-group success fraction.
  2. Why does complete-case regression change both sample size and potentially the population represented?
  3. What should a reproducible missingness audit report before comparing two fitted models?
Worked further solutions
  1. Lower bound 0.30, upper bound 0.50.
  2. Inclusion requires every needed variable to be observed. Those retained may differ systematically from those omitted.
  3. Missing counts by variable, overlapping patterns, the row inclusion rule, retained identifiers or a reproducible mask, and whether both models use the same observations.

Open chapter with navigation, interactive labs, and R examples →

Lesson 43 · Week 14

One Outcome, Several Predictors

An honest multivariable regression from a real environmental dataset.

Learning objectives:

  • Write and interpret a multivariable linear regression formula.
  • Distinguish an adjusted association from a causal effect.
  • Explain how complete-case selection and correlated predictors complicate interpretation.

We began with a simple regression: one response, one predictor, one straight line. Real problems are usually less cooperative.

Ozone concentration, for example, may change with several weather conditions. A naive association between ozone and temperature does not tell us how that association behaves after accounting for wind or solar radiation.

That is one reason multivariable thinking belongs in an introductory course, not a distant graduate elective.

Begin with real measurements

R’s built-in airquality dataset records ozone, solar radiation, wind, and temperature in New York during May–September 1973. It also records month and day. The original measurement sites and times differ by variable; our model is therefore a description of a historical daily dataset, not a controlled physical experiment.

First, ask a question we can honestly answer:

Among the days with complete measurements, how does the fitted mean ozone level change with recorded temperature, holding the other included predictors fixed?

This is an adjusted association question. It is not automatically a causal one.

Multiple regression is still a regression

An additive model could be written as

E(Y∣X1,X2,X3)=β0+β1X1+β2X2+β3X3,E(Y\mid X_1,X_2,X_3) =\beta_0+\beta_1X_1+\beta_2X_2+\beta_3X_3,

where YY is ozone in parts per billion, X1X_1 is temperature in degrees Fahrenheit, X2X_2 is wind speed in miles per hour, and X3X_3 is solar radiation in Langleys.

In this model, the coefficient β1\beta_1 describes the difference in the model’s conditional mean ozone value associated with one additional degree Fahrenheit holding wind and solar radiation constant.

That conditional phrase matters. It is the primary difference between interpreting a simple slope and interpreting a coefficient in a multiple regression.

Fit two models in R

The first uses temperature alone:

data("airquality", package = "datasets")
simple <- lm(Ozone ~ Temp, data = airquality)
summary(simple)

The second adds wind and solar radiation:

multiple <- lm(Ozone ~ Temp + Wind + Solar.R,
               data = airquality)
summary(multiple)

These models use different sets of complete observations: the multiple regression also requires nonmissing solar radiation. Comparing their coefficients directly therefore changes both the covariates and the sample.

We can isolate the model-specification question by fitting both models on the same complete-case subset:

complete <- na.omit(airquality[c("Ozone", "Temp", "Wind", "Solar.R")])
simple_same <- lm(Ozone ~ Temp, data = complete)
multiple_same <- lm(Ozone ~ Temp + Wind + Solar.R, data = complete)
coef(simple_same)
coef(multiple_same)

Now the comparison controls the analysis sample. Coefficient changes can still reflect correlated predictors, sampling variation, or model choices; they are not by themselves causal effects.

What about seasonality?

The dataset covers five months, not an entire year. Weather conditions, measurement patterns, and ozone concentrations can change over the season.

One possible exploratory extension adds month as a categorical predictor:

with_month <- lm(Ozone ~ Temp + Wind + Solar.R + factor(Month),
                 data = airquality)
summary(with_month)

This includes additional additive terms. It does not prove that we have fully adjusted for seasonality, nonlinearity, dependence between adjacent days, or all sources of confounding.

Questions before conclusions

A responsible analysis should ask whether there are extreme observations, whether residuals show curvature, whether error spread varies, whether daily observations are independent enough for the intended inference, and whether the historical measurement process supports the interpretation.

In particular, adding more predictors is not a mechanical path toward truth. Variables can be correlated, some may be consequences of others, and a high in-sample R2R^2 does not guarantee valid predictions outside the observed conditions.

The R Workbench example accompanying this lesson executes the missing-data audit, compares the models on a common sample, and displays plots. Change one assumption or formula at a time; record what changes and what remains uncertain.

Exercise

  1. In the additive model, how should a temperature coefficient be interpreted?
  2. Why compare simple and multiple models on a common set of complete observations?
  3. Why is neither of these observational models sufficient to estimate the causal effect of changing the weather?
Suggested responses
  1. As an adjusted association in the conditional mean ozone concentration per Fahrenheit degree, holding the other included predictors fixed, in the context of the fitted model.

  2. Otherwise the coefficient difference may reflect both added predictors and a change in which dates were included.

  3. The measurements were observational, potential confounding and dependence remain, and statistical adjustment alone does not establish a well-defined intervention or exchangeability.

Provenance

The dataset is bundled with base R, not copied into this repository. Consult the official R dataset documentation for the variable definitions, units, sources, and historical context. For why multivariable thinking belongs in introductory statistics, consult ASA GAISE Recommendation 5.

Keep the analysis sample fixed when comparing models

A model with more predictors can omit more records because it needs more nonmissing variables. To ask whether adding a predictor changes a coefficient or fit, first build a common complete-case mask using every variable needed by either model. Fit both models to that same subset, then report how the restriction differs from analyses using each model’s maximum available data. Otherwise a coefficient change can reflect new adjustment, a changed sample, or both.

In a multiple linear model Y=β0+β1X1+β2X2+εY=\beta_0+\beta_1X_1+\beta_2X_2+\varepsilon, the coefficient β1\beta_1 describes a conditional mean difference per unit of X1X_1 holding X2X_2 fixed under the model. It is not generally the coefficient from a separate bivariate fit. If predictors are correlated, their shared information and available combinations affect both estimation and uncertainty. A hypothetical comparison requiring combinations absent from the data may amount to extrapolation even when each individual variable lies within its marginal observed range.

The historical air-quality observations are ordered in time. Seasonal pattern and serial dependence should be inspected, not discarded by treating rows as interchangeable. A conventional lm summary does not test every design assumption. Also distinguish a prediction for a new day’s outcome from an estimated conditional mean; the former includes day-to-day residual variability.

Further practice

  1. Write the purpose of a common complete-case mask in one sentence.
  2. Explain what is being held fixed when interpreting an adjusted temperature coefficient.
  3. Suggest one sensitivity analysis that does not pretend the data constitute a randomized environmental experiment.
Worked further responses
  1. It holds the analyzed observations constant so a model comparison is not confounded by different row inclusion rules.
  2. The other included model predictors, with interpretation depending on their specification and observed support.
  3. Compare a time-adjusted model, inspect residuals by date, test a justified nonlinear mean term, or report sensitivity to influential days while preserving provenance and observational limits.

Open chapter with navigation, interactive labs, and R examples →

Lesson 44 · Week 14

Show Your Work, Including the Uncomfortable Parts

Research questions, data provenance, reproducible code, disclosure, and statistical reporting.

Learning objectives:

  • Write a report that documents provenance and analysis choices.
  • Separate descriptive findings from inferential and causal conclusions.
  • Build a reproducibility checklist.

A brilliant analysis that nobody can reproduce may be a brilliant story. But it is a terrible scientific artifact.

Reproducibility is not the claim that the result is correct. It is the more modest—and testable—claim that a reader can obtain the stated result from the same data and instructions.

Start with an empirical question

Write the question before the code. Define the population, unit of observation, outcome, relevant predictors, comparison, and the kind of conclusion the design supports.

“Does temperature cause ozone?” requires a causal study of interventions or strong causal identification assumptions.

“How were recorded ozone values associated with daily temperature in this historical dataset?” is an observational association question we can answer descriptively with properly documented data.

Preserve provenance

Record where the data originated, what dates they cover, what variables represent, which units they use, and whether anyone has permission to redistribute them.

Never quietly treat simulated numbers as observations from the world. Never turn a missing value into zero without disclosing and justifying the change.

For the R-distributed airquality field notebook, the original observations belong to a documented historical source and are distributed as part of R. We use them without relabeling them as our own research.

A minimal project structure

A transparent statistical project might include:

research-question.md
data-provenance.md
analysis.R
results.md
figures/
limitations.md

Every result in the final report should trace to a recorded dataset and reproducible analysis step. Specify software versions and random seeds when simulation is involved.

Report the quantities behind the headline

Include sample sizes, missing counts, relevant descriptive statistics, estimates with units, confidence intervals where appropriate, and the assumptions supporting inference.

A tiny p-value is not a substitute for an effect size. A high R2R^2 is not a prediction guarantee. An observational regression coefficient is not automatically a causal effect.

If the analysis explored many models before highlighting one, disclose the search. Exploration is legitimate; presenting it as a single preplanned confirmatory test is misleading.

The reader should be able to disagree

A good report makes limitations visible: measurement flaws, confounding, missing data, multiple comparisons, sampling-frame limits, unstable models, and the distinction between statistical and practical importance.

A source list with stable identifiers—preferably DOIs and convenient BibTeX—helps future scholars retrace your claims.

Check your understanding

  1. What does reproducibility establish, and what does it not establish?
  2. Why should an observational model’s conclusion avoid unsupported causal language?
  3. Which items should accompany a submitted analysis script?
Worked responses
  1. It allows the computation to be repeated. It does not prove assumptions, data quality, or scientific interpretation are valid.

  2. The design may not isolate interventions from confounders or selection mechanisms.

  3. Data source, dictionary, transformations, exclusions, software, versions, random seeds, and a clear question and interpretation.

Reproducibility is an executable chain of evidence

A useful analysis script begins with the documented source, validates the schema, applies explicit transformations, constructs the analysis population, computes results, and creates the reported tables. If a number was copied by hand from an exploratory console session, later rerunning a plotting script does not reproduce the full analysis. Record software versions, package requirements, random seeds for randomized algorithms, and acquisition dates for mutable sources.

A seed controls pseudorandom sequences for a specified implementation; it does not guarantee identical output across all software versions or make a statistical procedure scientifically valid. Record deterministic inputs and the algorithm as well. Keep exploratory work, prespecified confirmatory procedures, and later sensitivity analyses distinguishable in the report without concealing any of them.

A compact results paragraph identifies the target, design, sample and exclusions, estimate with units, uncertainty procedure, and limitations. For example, a hypothetical independent-sample mean difference of 2.5 points with a Welch interval [−1.56,6.56][-1.56,6.56] warrants reporting considerable uncertainty, not announcing “the groups are the same.” A reproducible script enables readers to verify arithmetic; a transparent argument enables them to challenge assumptions.

Further practice

  1. List the minimum information needed to reproduce a simulation-based p-value.
  2. Why should raw data and derived data be kept separately?
  3. What changes when a source updates its historical records after the report is written?
Worked further responses
  1. Data or a permitted access method, null model, statistic and extremeness rule, simulation algorithm, repetition count, seed, software versions, and handling of ties or corrections.
  2. Separation preserves original evidence and makes transformations auditable and repeatable.
  3. A fresh download may no longer reproduce the old result. Record version or retrieval date, preserve a permitted snapshot or checksum, and describe changes transparently.

Open chapter with navigation, interactive labs, and R examples →

Lesson 45 · Week 14

A Statistical Investigation from Question to Reproducible Report

Bring research design, visualization, estimation, models, and honest conclusions together.

Learning objectives:

  • Define a reproducible statistical research question using real data.
  • Select and justify an analysis that suits the data and design.
  • Report findings and uncertainty while describing unsupported causal interpretations.

You have reached the end of the textbook portion of this course. We can now ask a more interesting question than whether you remember the formula for a standard error.

Can you conduct a statistical investigation from beginning to end without deceiving yourself or your reader?

That is the capstone.

The research brief

Start with a question that can be answered using genuinely observed, documented data. The provided starting dataset is R’s historical airquality records from New York in 1973.

One suitable question is:

Among the observed days with complete measurements, how does recorded ozone concentration relate to temperature, wind, and solar radiation?

That is a descriptive and model-based question. It is deliberately not “What is the causal effect of increasing temperature by one degree on ozone?” You do not have an experiment manipulating the weather.

Alternatively, use another verifiably sourced dataset whose use is permitted, with a data dictionary and enough observations to support a suitable analysis.

1. Frame the investigation

Identify the population you would like to understand and the actual observational units represented by the records. Define the response variable, predictors, time range, measurement units, and how observations were selected.

Write down which claim the design could support. If the evidence is observational, explain which sources of confounding, selection, or temporal structure prevent you from assuming causality.

2. Audit the source

For the provided R dataset:

data("airquality", package = "datasets")
dim(airquality)
colSums(is.na(airquality))
summary(airquality)

You should find 153 rows. There are 37 missing ozone values and seven missing solar-radiation values. A model containing ozone, solar radiation, wind, and temperature uses only 111 complete observations with the default missingness handling.

Explain what was lost, what remains, and why missingness may matter for generalization.

3. Explore before modeling

Make at least two appropriate visualizations. One should show the response variable’s distribution; another should investigate its association with a predictor or the structure of missingness.

Summarize center and spread with justified choices. If the data are skewed, explain why the median or quantiles might complement a mean. Label every plotted unit and source.

Do not allow the default graphing software to decide your scientific interpretation.

4. Specify and calculate

For an air-quality analysis, a plausible model is:

E(Ozone∣Temp,Wind,Solar.R)=β0+β1Temp+β2Wind+β3Solar.R.E(\mathrm{Ozone}\mid \mathrm{Temp},\mathrm{Wind},\mathrm{Solar.R}) =\beta_0+\beta_1\mathrm{Temp} +\beta_2\mathrm{Wind}+\beta_3\mathrm{Solar.R}.

You can reproduce it in R:

required <- c("Ozone", "Temp", "Wind", "Solar.R")
complete <- na.omit(airquality[required])
fit <- lm(Ozone ~ Temp + Wind + Solar.R, data = complete)
summary(fit)
plot(fitted(fit), resid(fit))
abline(h=0, lty=2)

Identify the number of analytic observations, estimated coefficients with their units, and at least one appropriate uncertainty summary. Inspect the residual plot and discuss violations or ambiguities.

To compare the temperature-only model with the multivariable model, fit both on the same complete-case records. Otherwise a changed coefficient can be due to both a new specification and a changed sample.

5. Test an alternative explanation

What happens if you add month as a factor? What happens if you use only temperature and wind? Would a curved temperature term improve the descriptive fit? You need not try every conceivable model. Choose one scientifically motivated sensitivity analysis and explain what question it answers.

Disclose every alternative you tried. Do not simply select the model with the most appealing p-value and pretend that it was the original plan.

6. Write an actual report

Submit a concise report with:

  1. Research question and design. What are you estimating, for whom, and from which observations?
  2. Source and provenance. Who recorded the data? When? How can someone recover the source?
  3. Data audit. Observation count, missingness, exclusions, definitions, and transformations.
  4. Visual exploration. Two figures with captions that stand on their own.
  5. Methods. Equations or algorithms, assumptions, and why they fit the question.
  6. Results. Estimates, units, uncertainty, and the principal findings.
  7. Sensitivity and limitations. One alternative analysis, possible bias, and the distinction between association and causation.
  8. Reproducible code. An R script that runs on a clean installation with the specified dataset.

The reproducibility requirement is not optional. If the script cannot recreate the results from the documented source, revise the submission.

Scoring rubric (100 points)

Criterion Points
Well-scoped empirical question and design 10
Verified provenance, dictionary, and reproducibility 15
Missingness and data-quality audit 15
Appropriate, clearly labeled visualizations 10
Correct statistical method and assumptions 20
Correct interpretation of estimates and uncertainty 15
Sensitivity analysis, ethics, and limitations 10
Clear, concise, transparent communication 5
Total 100

A report should not receive full credit on the methods or interpretation criteria if it makes unsupported causal claims, misreports denominators, or conceals exclusions.

Final self-critique

Before submitting, answer these questions in a short paragraph:

  • Which conclusion would a statistically inexperienced reader be most likely to draw incorrectly?
  • What important information is missing from your dataset?
  • Would you be comfortable sharing the source and code with someone determined to prove you wrong?
  • If you had resources for one better follow-up study, how would you design it?

What completion means

Completing this project is stronger evidence of competence than clicking through a lecture. Yet it is not a licensed university credential. The surrounding project is independent educational material, and an instructor would still need to assess the submitted work.

The outcome we want is not merely a student who can calculate. It is someone who can look at a quantitative claim, ask where the data came from, and know exactly what the mathematics does—and does not—establish.

Starting sources

A reference structure for the final report

Use a title that names the actual question, followed by an abstract stating the design, data, main estimate, uncertainty, and principal limitation. In the methods section define the unit of observation, inclusion rules, missingness handling, transformations, estimand, model assumptions, and any planned comparisons. A reader should be able to reconstruct which rows produced every denominator.

The results should begin with the analysis sample and its descriptive distribution, then present the primary estimate with units and uncertainty. Separate a primary model from exploratory extensions. Explain at least one plausible alternative explanation or modeling choice and report how it changes the conclusion. A discussion should distinguish the population directly described by the observations from any broader population or causal claim being considered.

Include an executable script, a data dictionary, source and rights information, and a short computational checklist. Confirm that code can run in a clean session, tables agree with the prose, and a changed seed does not overturn a Monte Carlo conclusion merely because too few repetitions were used. Where exact computation is possible, compare it with simulation.

A self-contained design critique

A hypothetical city posts an online questionnaire and receives 2,000 replies, 70% supporting a park. A report declares that citywide support is 70%±2%70\%\pm2\%. The respondent proportion is descriptive evidence. Its generalization to residents requires a selection and response model. A textbook independent-sample margin does not account for self-selection merely because the reply count is large. A defensible capstone would identify the unsupported inferential step, state what the data do establish, and propose a sampling design or sensitivity analysis rather than attach a more complicated formula to the same unsupported claim.

Final oral-defense prompts

  1. What exactly is your estimand, and which population does it concern?
  2. Which assumption would most damage your conclusion if false?
  3. Which numerical result can another reader independently verify?
  4. What additional data would most reduce the uncertainty you actually face?
What a satisfactory defense demonstrates

There is no single numerical answer. A satisfactory response ties the estimand to the design, identifies assumptions beyond software syntax, reproduces at least one calculation from documented inputs, and distinguishes sampling precision from bias or causal uncertainty. More observations are useful only if they address the relevant information gap.

Open chapter with navigation, interactive labs, and R examples →

Complete the investigation

Reading mathematics is an excellent beginning. The course ends with a reproducible research capstone, fourteen weekly applied assignments, and four formative unit assessments. The interactive labs and R Workbench are available online.

For corrections and editorial questions, visit James Howard’s website. This expanded November 2026 manuscript remains under review; no blanket public license is granted at this stage.