Reference sheet

Statistics reference sheet

The main definitions, formulas, tests and conditions of the statistics course on one page, unit by unit, with links to the lessons that explain each topic in full.

For Statistics

This sheet follows the twelve units of the course in order. Each unit starts with the big idea in a few sentences, then gives the definitions, formulas, rules and procedures you will look up most often, with the conditions they need. When you want the full explanation, a derivation or more examples, follow the lesson links under each topic.

Population quantities, called parameters, are the population mean μ\mu, the population proportion pp and the population standard deviation σ\sigma. The matching sample statistics are the sample mean xˉ\bar{x}, the sample proportion p^\hat{p} and the sample standard deviation ss, which divides by n−1n - 1. A capital letter such as XX names a random variable and a lowercase letter an observed value, so Xˉ\bar{X} is the sample mean before the data are collected and xˉ\bar{x} is its observed value. Probabilities are written P(A)P(A) and P(A∣B)P(A \mid B), and a random variable has expected value E(X)E(X), variance Var⁡(X)\operatorname{Var}(X) and standard deviation SD⁡(X)\operatorname{SD}(X). The standard error SE⁡\operatorname{SE} of a statistic is the standard deviation of its sampling distribution, and SE⁡^\widehat{\operatorname{SE}} is an estimate of it computed from the data.

A normal distribution is written N(μ,σ2)N(\mu, \sigma^2) with its variance, ZZ stands for a standard normal variable and Φ\Phi for its CDF. Quantiles are lower-tail quantiles. The qq quantile of N(0,1)N(0, 1) is zqz_q, so Φ(zq)=q\Phi(z_q) = q, and tq,νt_{q,\nu}, χq,ν2\chi^2_{q,\nu} and Fq; d1,d2F_{q;\,d_1,d_2} are the qq quantiles of the tνt_\nu, χν2\chi^2_\nu and Fd1,d2F_{d_1,d_2} distributions, whose subscripts ν\nu, d1d_1 and d2d_2 are degrees of freedom. A two-sided 95 percent procedure therefore uses z0.975≈1.960z_{0.975} \approx 1.960. Hypotheses are H0H_0 and H1H_1, and α\alpha is the significance level unless a topic gives it another meaning. Logarithms are natural logarithms, and ≈\approx marks a rounded or approximate value.

Statistical Thinking and Data

Statistics starts with a question about a group and a clear idea of what each recorded value means. A number computed from data describes the units that were observed, and a statement about any other units needs an argument about how the data were produced.

Populations, samples, parameters and statistics

A statistical question asks about a defined collection of units and expects the answers to vary from unit to unit. The observational unit is the person, thing or event that one row of data describes. The population is the complete set of units the question is about, of size NN, and a sample is the part of it on which data are collected, of size nn. A census collects data on every unit.

QuantityPopulation parameterSample statistic
Meanμ\muxˉ=x1+⋯+xnn\bar{x} = \dfrac{x_1 + \cdots + x_n}{n}
Proportion with a propertyppp^=kn\hat{p} = \dfrac{k}{n} when kk of the nn units have it
Standard deviationσ\sigmass

For a fixed population a parameter is one number, usually unknown. A statistic is known once the data are in, but its value changes from sample to sample, which is sampling variability, and for one sample the difference xˉ−μ\bar{x} - \mu is its sampling error. Descriptive statistics summarizes the data at hand. Inferential statistics draws conclusions about a larger population, a process or a cause, with a statement of uncertainty, and that step needs random sampling, random assignment or a model for how the data arose.

For example, six waits of 2, 3, 4, 5, 7 and 9 minutes have xˉ=30/6=5\bar{x} = 30/6 = 5 minutes, and two of the six exceed 6 minutes, so p^=1/3\hat{p} = 1/3. Six other visits from the same population would usually give other values.

Lessons Introduction to Statistics

Variables and levels of measurement

A variable is a characteristic recorded for each unit. A categorical variable places a unit in one of several categories, and a numerical variable records an amount in stated units, so that differences and averages of its values are amounts of the same thing. Identifiers and numeric codes for categories stay categorical. A numerical variable is discrete when its possible values form a finite or countable list, such as counts, and continuous when, in the model used, it can take any value in an interval.

LevelValuesComparisons that make senseExample
Nominalcategories without an ordersame or different, counts, proportions, modeblood type
Ordinalordered categoriesalso order and ranks, but not the sizes of the stepsrating from poor to excellent
Intervalnumbers in equal units with an arbitrary zeroalso differences and meanstemperature in degrees Celsius
Ratioan interval scale whose zero means none of the quantityalso ratioswaiting time in minutes

An operational definition says exactly how a value is obtained, including the instrument, the units, the recording resolution and how a missing value is marked. Accuracy is closeness to the true value, and precision is agreement among repeated measurements. A binary indicator is 11 for a unit that meets a condition and 00 otherwise, and the mean of the indicators is the proportion of units that meet it.

Ratios fail on an interval scale. The temperatures 1010 and 2020 degrees Celsius are 5050 and 6868 degrees Fahrenheit, and 68/50=1.3668/50 = 1.36, not 22. Differences convert consistently, since a change of 1010 Celsius degrees is always a change of 1818 Fahrenheit degrees.

Lessons Types of Data and Measurement

Data tables and data quality

A data table gives each observational unit a row and each variable a column. The data dictionary records each variable’s meaning, units, allowed values and missing-value code, and the provenance records who produced the data, how the units were selected and how the file reached the analyst. The raw data stay unchanged, and every edit goes into a dated data cleaning log with its reason.

  • Missing values. A missing value is not zero. Four observed values totaling 105 have mean 26.2526.25, while recording a fifth, missing value as zero gives 105/5=21105/5 = 21, an average that includes a value nobody measured.
  • Duplicates. A duplicate record is the same unit on the same occasion entered more than once. Equal values alone do not show that two records are duplicates.
  • Outliers. An outlier lies unusually far from the bulk of the data. It is a reason to check the value, not evidence of an error, since it can be a mistake, a unit from outside the population or a genuine extreme.
Missingness mechanismThe chance that a value is missingMean of the complete cases
Missing completely at randomdepends on none of the datano systematic error, only less precision
Missing at randomdepends only on recorded variablescan be biased, and methods that use those variables can correct it under this assumption
Missing not at randomdepends on the missing value itself, even given the recorded variablescan be biased, and the data alone cannot show by how much

A complete-case analysis drops every record with a missing value on the variables it needs, so its results describe the complete cases. They answer a question about all the intended units only under an assumption about the mechanism.

Lessons Data Tables, Missing Values and Data Quality

Describing and Exploring Data

Tables, graphs and a few numbers describe what a set of data shows. Center, spread, position and shape summarize one variable, while scatter plots, correlation and two-way tables describe how two variables vary together. Each summary answers a particular question, so the question and the shape of the data decide which one to use.

Frequency tables and categorical charts

The frequency of a category is its count. When the categories are mutually exclusive and exhaustive, the frequencies add to nn, and the relative frequency of a category with frequency ff is f/nf/n. A bar chart draws one bar per category, separated by gaps, with lengths measured from a baseline at zero. A contingency table cross-classifies two categorical variables, its row and column totals are the margins, and a conditional percentage uses one row or one column as its denominator.

For example, if 12 of 25 people use the bus and 8 of the 10 people in group A do, then 80 percent of group A use the bus, while group A makes up 8/12≈66.78/12 \approx 66.7 percent of bus users. The two percentages have different denominators and answer different questions.

Cumulative frequencies are meaningful only for ordered categories or numerical values. In a multiple-response question a respondent may choose several categories, so the percentages of respondents can add to more than 100 percent.

Lessons Frequency Tables and Categorical Charts

Dot plots, histograms and distribution shape

A dot plot shows one dot per observation. A histogram divides an interval containing the data into adjacent bins and draws touching bars. When the bins have different widths, the height of each bar must be its frequency density, so that areas show counts. A bin of width wjw_j holding njn_j observations gets

hj=njwj,∑jhjwj=n,\begin{gathered} h_j = \frac{n_j}{w_j}, \\[0.4em] \sum_j h_j w_j = n, \end{gathered}

and dividing by nn as well gives bars with total area 11. A bin from 0 to 2 and a bin from 2 to 8 that each hold 6 observations have heights 33 and 11 and equal areas.

Describe a distribution by its shape, center, spread and unusual values. It is skewed to the right when its right tail stretches much farther from the bulk than its left tail, and its modality is the number of clear peaks. The apparent shape can depend on the choice of bins, especially in a small sample.

Lessons Dot Plots, Histograms and Distribution Shape

Center

MeasureDefinitionProperties
Meanxˉ=1n∑i=1nxi\bar{x} = \dfrac{1}{n}\displaystyle\sum_{i=1}^{n} x_ibalance point with ∑(xi−xˉ)=0\sum (x_i - \bar{x}) = 0, pulled toward extreme values
Medianthe middle ordered value, or the average of the two middle values when nn is evenresistant to a few extreme values
Modethe most frequent value or categorycan be several, and the only one of the three for nominal data
Weighted meanxˉw=∑wixi∑wi\bar{x}_w = \dfrac{\sum w_i x_i}{\sum w_i} with wi≥0w_i \ge 0 and ∑wi>0\sum w_i > 0combines group means when the weights are the group sizes

The values 2, 3, 4, 5 and 16 have mean 6 and median 4. Changing 16 to 26 moves the mean to 8 and leaves the median at 4. Combining groups of 2 and 8 people with means 10 and 20 gives the overall mean (2⋅10+8⋅20)/10=18(2 \cdot 10 + 8 \cdot 20)/10 = 18, not the unweighted average 15.

Lessons Mean, Median, Mode and Weighted Averages

Variance and standard deviation

For all NN values of a finite population with mean μ\mu, and for a sample of n≥2n \ge 2 values with mean xˉ\bar{x},

σ2=1N∑i=1N(xi−μ)2,s2=1n−1∑i=1n(xi−xˉ)2.\begin{gathered} \sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i - \mu)^2, \\[0.4em] s^2 = \frac{1}{n - 1}\sum_{i=1}^{n}(x_i - \bar{x})^2 . \end{gathered}

The standard deviations σ\sigma and ss are the nonnegative square roots, in the units of the data, while variances are in squared units. A standard deviation is 00 exactly when all the values are equal. The sample variance divides by the n−1n - 1 degrees of freedom because the deviations from xˉ\bar{x} add to zero, and for independent observations from a population with variance σ2\sigma^2 this gives E(S2)=σ2E(S^2) = \sigma^2.

The values 2, 4, 6 and 8 have mean 5 and squared deviations adding to 20. As a whole population they have σ2=5\sigma^2 = 5 and σ≈2.236\sigma \approx 2.236, and as a sample s2=20/3s^2 = 20/3 and s≈2.582s \approx 2.582.

Lessons Variance and Standard Deviation

Percentiles, quartiles and box plots

A ppth percentile has about pp percent of the data below it. Sample percentiles need a stated rule, and the common rules can disagree in small samples. Under the median-of-halves rule, Q1Q_1 and Q3Q_3 are the medians of the lower and upper halves of the ordered data, with the middle value left out of both halves when nn is odd. Then

IQR=Q3−Q1,L=Q1−1.5 IQR,U=Q3+1.5 IQR.\begin{gathered} \text{IQR} = Q_3 - Q_1, \\[0.4em] L = Q_1 - 1.5\,\text{IQR}, \\[0.4em] U = Q_3 + 1.5\,\text{IQR}. \end{gathered}

The five-number summary lists the minimum, Q1Q_1, the median, Q3Q_3 and the maximum. A box plot draws a box from Q1Q_1 to Q3Q_3 with a line at the median. In the modified box plot the whiskers stop at the most extreme values that are not beyond the fences LL and UU, and values below LL or above UU are drawn as points and flagged as potential outliers.

Two more resistant summaries are the median absolute deviation, MAD⁡=median⁡i∣xi−m∣\operatorname{MAD} = \operatorname{median}_i \lvert x_i - m \rvert for the median mm, and the trimmed mean, which drops the kk smallest and the kk largest values, with 2k<n2k < n, and averages the rest. Some software multiplies the MAD by about 1.48261.4826, so a report says which version it gives.

For delays of 1, 2, 3, 4, 5, 6, 7 and 20 minutes, Q1=2.5Q_1 = 2.5, the median is 4.54.5 and Q3=6.5Q_3 = 6.5, so the IQR is 4 and the fences are −3.5-3.5 and 12.512.5. Only the delay of 20 minutes is flagged. The mean is 6, while the MAD is 2 and the mean trimmed by one value at each end is 4.54.5.

Lessons Percentiles, Quartiles and Box Plots

Z-scores and changes of scale

The z-score of a value xx relative to a distribution with mean μ\mu and standard deviation σ>0\sigma > 0 is

z=x−μσ,z = \frac{x - \mu}{\sigma},

and for a sample xˉ\bar{x} and ss take the places of μ\mu and σ\sigma. It counts standard deviations above or below the mean, and standardized data have mean 00 and standard deviation 11. For a linear transformation yi=a+bxiy_i = a + bx_i of every value,

SummaryEffect
Mean and medianyˉ=a+bxˉ\bar{y} = a + b\bar{x}, and the median changes the same way
Standard deviation and IQRmultiplied by ∣b∣\lvert b \rvert
Variancemultiplied by b2b^2
z-scoresunchanged when b>0b > 0, sign reversed when b<0b < 0

A shift alone changes no measure of spread. Temperatures with mean 20 and SD 5 degrees Celsius have mean 32+1.8⋅20=6832 + 1.8 \cdot 20 = 68 and SD 1.8⋅5=91.8 \cdot 5 = 9 in degrees Fahrenheit, and 30 degrees Celsius, which is 86 degrees Fahrenheit, has z=2z = 2 on both scales.

Lessons Z-Scores and Changes of Scale

Comparing distributions and reading graphs

Compare groups on a common scale, looking at center, spread, shape, unusual values and the number of observations behind each group. The length of a bar must start from a meaningful baseline, normally zero. For a change from aa to bb, with a>0a > 0 for the relative change,

absolute change=b−a,relative change=b−aa.\begin{gathered} \text{absolute change} = b - a, \\[0.4em] \text{relative change} = \frac{b - a}{a}. \end{gathered}

A change between two percentages is measured in percentage points, so a rise from 10 percent to 15 percent is 5 percentage points and a relative increase of 50 percent. Counts compare groups only when the denominators match, and 20 events among 1000 people and 80 among 2000 are rates of 2 and 4 percent. Graphs mislead through truncated baselines, side-by-side panels on different scales, unequal histogram bins drawn with frequency heights, uneven time axes and icons enlarged in both directions.

Lessons Comparing Distributions and Reading Graphs

Scatter plots, covariance and correlation

For n≥2n \ge 2 pairs (xi,yi)(x_i, y_i) measured on the same individuals, the sample covariance and the Pearson correlation are

sxy=∑i=1n(xi−xˉ)(yi−yˉ)n−1,r=sxysxsy.\begin{gathered} s_{xy} = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{n - 1}, \\[0.4em] r = \frac{s_{xy}}{s_x s_y} . \end{gathered}

The covariance is in the product of the two units. The correlation needs sx>0s_x > 0 and sy>0s_y > 0, has no units and satisfies −1≤r≤1-1 \le r \le 1, with r=±1r = \pm 1 exactly when all the points lie on one straight line, rising for r=1r = 1 and falling for r=−1r = -1. It does not change when either variable is shifted or multiplied by a positive constant, and it changes sign when one variable is multiplied by a negative constant.

Correlation measures only linear association. The points (−1,1)(-1, 1), (0,0)(0, 0) and (1,1)(1, 1) lie exactly on the curve y=x2y = x^2 and have r=0r = 0. A single influential point, or data that cover only part of the range of a variable, can change rr a lot. The Spearman rank correlation rsr_s is the Pearson correlation of the ranks, with tied values given the average of their ranks, and it measures monotonic association. Neither coefficient shows that one variable causes the other.

Lessons Scatter Plots, Covariance and Correlation

Two-way tables and Simpson’s paradox

The aggregated proportion of a group is a weighted average of its subgroup proportions, each weighted by that subgroup’s share of the group’s cases,

p^=∑knkn p^k.\hat{p} = \sum_{k} \frac{n_k}{n}\,\hat{p}_k .

Simpson’s paradox occurs when an association has the same direction in every subgroup but reverses or disappears once the subgroups are combined. It can happen only when the groups being compared are spread differently over the subgroups.

Easy casesHard casesAll cases
Service A9/10=0.909/10 = 0.9027/90=0.3027/90 = 0.3036/100=0.3636/100 = 0.36
Service B72/90=0.8072/90 = 0.802/10=0.202/10 = 0.2074/100=0.7474/100 = 0.74

Service A has the higher success rate for both kinds of case and the lower rate overall, because most of its cases are hard. A standardized rate applies one fixed mixture of subgroups to every group. With half easy and half hard cases, A scores 0.5(0.90)+0.5(0.30)=0.600.5(0.90) + 0.5(0.30) = 0.60 and B scores 0.500.50. Which comparison answers the question, and whether the subgroup variable is a confounder, depends on the causal setting, not on the arithmetic.

Lessons Two-Way Tables and Simpson’s Paradox

Collecting Trustworthy Data

How data are collected decides which conclusions they can support. A biased selection stays biased however large the sample, random sampling supports generalizing to the population that was sampled, and random assignment supports conclusions about cause and effect.

Sampling bias and representativeness

The target population is the set of units a study wants to describe, and the sampling frame is the list or procedure from which units are actually selected. Selection bias is a systematic difference between the analyzed units and the target population, and a larger sample from the same process does not remove it.

SourceWhat goes wrong
Undercoveragepart of the target population is missing from the frame or cannot be reached
Nonresponseselected units do not respond, and responders differ from nonresponders
Voluntary responsepeople select themselves, often those with strong views
Measurement biasquestion wording, the interviewer, the wish to give an acceptable answer or a faulty instrument shifts the recorded values

If a share cc of the target population is covered, with 0<c<10 < c < 1, proportion pCp_C among the covered units and pUp_U among the others, then

p=c pC+(1−c) pU,pC−p=(1−c)(pC−pU).\begin{gathered} p = c\,p_C + (1 - c)\,p_U, \\[0.4em] p_C - p = (1 - c)(p_C - p_U). \end{gathered}

The error is the uncovered share times the gap, whatever the sample size. With c=0.2c = 0.2, pC=0.90p_C = 0.90 and pU=0.50p_U = 0.50, the target proportion is 0.580.58 and the covered units overstate it by 0.320.32. The same calculation applies to nonresponse, with respondents in place of covered units. A sample is representative for a question when its selection and measurement give no systematic tendency to misstate the answer, which is a property of the process, not of how one sample looks.

Lessons Sampling Bias and Representativeness

Random sampling methods

A probability sample gives every unit of the frame a known, positive inclusion probability πi\pi_i, and the design weight of a sampled unit is wi=1/πiw_i = 1/\pi_i.

DesignHow units are selectedInclusion probability
Simple random sampleevery set of nn of the NN units is equally likelyn/Nn/N
Stratifieda separate simple random sample of nhn_h units from each stratum of NhN_h unitsnh/Nhn_h/N_h in stratum hh
Clustera probability sample of whole groups, observing all units in eachthe probability that the unit’s cluster is chosen
Systematica start rr chosen with equal probabilities from 11 to kk, then every kkth unit of the list1/k1/k

With unequal inclusion probabilities, estimate a proportion by the weighted proportion p^w=∑wiyi/∑wi\hat{p}_w = \sum w_i y_i / \sum w_i, where both sums run over the sample and yiy_i is a 0/1 indicator. Sampling 10 of 20 units in one stratum and 10 of 80 in another gives weights 2 and 8. If 8 and 2 of the sampled units have the property, the weighted proportion is (8⋅2+2⋅8)/(10⋅2+10⋅8)=0.32(8 \cdot 2 + 2 \cdot 8)/(10 \cdot 2 + 10 \cdot 8) = 0.32, while the unweighted 10/20=0.5010/20 = 0.50 overrepresents the small stratum.

The design effect of an estimator θ^\hat{\theta} compares its variance under the design with its variance under simple random sampling of the same size from the same frame,

DEFF=Var⁡design(θ^)Var⁡SRS(θ^),\text{DEFF} = \frac{\operatorname{Var}_{\text{design}}(\hat{\theta})}{\operatorname{Var}_{\text{SRS}}(\hat{\theta})} ,

and n/DEFFn/\text{DEFF} is the effective sample size. Stratifying on a variable related to the response often brings it below 1, and sampling clusters of similar units often pushes it above 1, but the value depends on the population, the estimator and the variable measured.

Lessons Random Sampling Methods

Observational studies, confounding and causation

In an observational study the researcher records the explanatory variable and the response but does not assign the explanatory variable. For a unit ii with potential outcomes Yi(1)Y_i(1) under treatment and Yi(0)Y_i(0) under control, the causal effect is τi=Yi(1)−Yi(0)\tau_i = Y_i(1) - Y_i(0), and at most one of the two outcomes is ever observed, so τi\tau_i is never observed directly. An association between the explanatory variable and the response can come from

  • a causal effect of the explanatory variable,
  • confounding, a factor associated with the explanatory variable that also affects the response,
  • reverse causation, where the response or an early stage of it affects the explanatory variable,
  • selection, when entry into the analysis depends on both variables,
  • chance variation.

Adjusting for a measured confounder, for example by comparing units with similar values of it, removes confounding by that variable only as far as the compared units really are similar, and unmeasured confounders remain.

Lessons Observational Studies, Confounding and Causation

Randomized experiments

In an experiment the investigator assigns treatments to experimental units, the entities that can receive different treatments. Random assignment by a chance mechanism balances measured and unmeasured characteristics on average over the possible assignments, which supports a causal comparison of the treatments for the units studied.

  • Control and placebo. A control group receives a comparison condition, and a placebo imitates the treatment without its active component.
  • Blinding. Some or all of the participants, the staff delivering treatments and the people assessing outcomes are kept from knowing the assignments, and a report says exactly who was blinded.
  • Replication. Each treatment goes to several experimental units. Repeated measurements of one unit are not replicates.
  • Blocking. Treatments are randomized separately within blocks of similar units and compared within blocks, which keeps block differences out of the comparison. A matched pairs design uses blocks of two and analyzes the within-pair differences.
Random assignmentNo random assignment
Random samplecausal conclusion that extends to the sampled populationassociation that extends to the sampled population
No random samplecausal conclusion for the units studiedassociation among the units studied

Lessons Randomized Experiments, Blocking and Matched Pairs

Probability Models for Statistics

Probability describes chance through a model, and statistical inference rests on such models. The rules for events lead to conditional probability and Bayes’ theorem, random variables turn outcomes into numbers, and a few standard distributions model counts, waiting times and measurements.

Probability rules, conditioning and independence

A sample space Ω\Omega contains all possible outcomes, an event is a set of outcomes, and a probability model gives each event a number with 0≤P(A)≤10 \le P(A) \le 1, P(Ω)=1P(\Omega) = 1 and the probabilities of disjoint events adding. When a finite sample space has equally likely outcomes, P(A)P(A) is the number of outcomes in AA divided by the number in Ω\Omega.

RuleFormulaCondition
ComplementP(Ac)=1−P(A)P(A^c) = 1 - P(A)any event
AdditionP(A∪B)=P(A)+P(B)−P(A∩B)P(A \cup B) = P(A) + P(B) - P(A \cap B)any two events
Disjoint eventsP(A∪B)=P(A)+P(B)P(A \cup B) = P(A) + P(B)A∩B=∅A \cap B = \varnothing
Conditional probabilityP(A∣B)=P(A∩B)P(B)P(A \mid B) = \dfrac{P(A \cap B)}{P(B)}P(B)>0P(B) > 0
MultiplicationP(A∩B)=P(B) P(A∣B)P(A \cap B) = P(B)\,P(A \mid B)P(B)>0P(B) > 0
IndependenceP(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B)the definition
Total probabilityP(A)=∑iP(A∣Bi) P(Bi)P(A) = \sum_i P(A \mid B_i)\,P(B_i)BiB_i disjoint and exhaustive, each P(Bi)>0P(B_i) > 0

When P(B)>0P(B) > 0, independence means P(A∣B)=P(A)P(A \mid B) = P(A). Disjoint events with positive probabilities are never independent, since one rules out the other. For a fair die, the events A={2,4,6}A = \{2, 4, 6\} and B={4,5,6}B = \{4, 5, 6\} give P(A∪B)=3/6+3/6−2/6=2/3P(A \cup B) = 3/6 + 3/6 - 2/6 = 2/3, and since P(A∩B)=1/3P(A \cap B) = 1/3 differs from P(A) P(B)=1/4P(A)\,P(B) = 1/4, they are not independent. In repeated independent trials the relative frequency of an event tends to its probability, which is the long-run reading of probability.

Lessons Probability Rules and Events, Conditional Probability and Independence

Bayes’ theorem and base rates

For a condition DD with 0<P(D)<10 < P(D) < 1 and a positive test result, written ++, with P(+)>0P(+) > 0,

P(D∣+)=P(+∣D) P(D)P(+),P(+)=P(+∣D) P(D)+P(+∣Dc) P(Dc).\begin{aligned} &P(D \mid +) \\[0.4em] &\quad = \frac{P(+ \mid D)\,P(D)}{P(+)}, \\[0.8em] &P(+) = P(+ \mid D)\,P(D) \\[0.4em] &\qquad + P(+ \mid D^c)\,P(D^c). \end{aligned}
TermProbability
Base rate or prevalence, the priorP(D)P(D)
SensitivityP(+∣D)P(+ \mid D)
SpecificityP(−∣Dc)P(- \mid D^c)
False-positive rateP(+∣Dc)=1−specificityP(+ \mid D^c) = 1 - \text{specificity}
Positive predictive valueP(D∣+)P(D \mid +)
Negative predictive valueP(Dc∣−)P(D^c \mid -)

The predictive values depend on the base rate as well as on the test. With base rate 0.100.10, sensitivity 0.900.90 and specificity 0.950.95, natural frequencies for 1000 people give 90 true positives and 45 false positives, so P(D∣+)=90/135=2/3P(D \mid +) = 90/135 = 2/3. With a base rate of 0.020.02 the same test gives P(D∣+)=18/67≈0.269P(D \mid +) = 18/67 \approx 0.269. Reading the sensitivity P(+∣D)P(+ \mid D) as if it were P(D∣+)P(D \mid +) ignores the base rate.

Lessons Bayes’ Theorem and Base Rates

Counting and sampling without replacement

If a procedure has kk stages with n1,n2,…,nkn_1, n_2, \dots, n_k possible results at the successive stages, whatever happened before, it has n1n2⋯nkn_1 n_2 \cdots n_k possible results in all. For whole numbers 0≤k≤n0 \le k \le n, with 0!=10! = 1,

Selections of kk from nn distinct objectsNumber
Ordered, with replacementnkn^k
Ordered, without replacementn!(n−k)!\dfrac{n!}{(n - k)!}
Unordered, without replacement(nk)=n!k! (n−k)!\dbinom{n}{k} = \dfrac{n!}{k!\,(n - k)!}

Draws without replacement are dependent. From 8 items of which 3 are marked, a sample of 3 drawn without replacement, with every set of 3 equally likely, contains exactly 2 marked items with probability (32)(51)/(83)=15/56\binom{3}{2}\binom{5}{1}/\binom{8}{3} = 15/56, and no marked item with probability 10/56≈0.17910/56 \approx 0.179, not the (5/8)3≈0.244(5/8)^3 \approx 0.244 that independent draws with replacement would give.

Lessons Counting and Sampling Without Replacement

Random variables, expected value and variance

A random variable assigns a number to each outcome. A discrete random variable has a probability mass function pX(x)=P(X=x)p_X(x) = P(X = x) whose values are nonnegative and add to 1 over its support, the set of values with positive probability. Every random variable has a cumulative distribution function FX(x)=P(X≤x)F_X(x) = P(X \le x), which never decreases and runs from 0 to 1, and P(a<X≤b)=FX(b)−FX(a)P(a < X \le b) = F_X(b) - F_X(a) for a<ba < b.

For a discrete XX with mean μ=E(X)\mu = E(X),

E(X)=∑xx pX(x),Var⁡(X)=E[(X−μ)2]=E(X2)−μ2,\begin{aligned} E(X) &= \sum_x x\,p_X(x), \\[0.4em] \operatorname{Var}(X) &= E\big[(X - \mu)^2\big] \\[0.4em] &= E(X^2) - \mu^2, \end{aligned}

provided ∑x∣x∣ pX(x)\sum_x \lvert x \rvert\,p_X(x) is finite for the mean and E(X2)E(X^2) is finite for the variance, and SD⁡(X)=Var⁡(X)\operatorname{SD}(X) = \sqrt{\operatorname{Var}(X)}.

RuleCondition
E(aX+bY+c)=aE(X)+bE(Y)+cE(aX + bY + c) = aE(X) + bE(Y) + cfinite means, independence not needed
Var⁡(aX+b)=a2Var⁡(X)\operatorname{Var}(aX + b) = a^2\operatorname{Var}(X)finite variance
Cov⁡(X,Y)=E(XY)−E(X) E(Y)\operatorname{Cov}(X, Y) = E(XY) - E(X)\,E(Y)finite variances
Var⁡(X±Y)=Var⁡(X)+Var⁡(Y)±2Cov⁡(X,Y)\operatorname{Var}(X \pm Y) = \operatorname{Var}(X) + \operatorname{Var}(Y) \pm 2\operatorname{Cov}(X, Y)finite variances
Var⁡(X±Y)=Var⁡(X)+Var⁡(Y)\operatorname{Var}(X \pm Y) = \operatorname{Var}(X) + \operatorname{Var}(Y)finite variances, XX and YY uncorrelated, for example independent
E(XY)=E(X) E(Y)E(XY) = E(X)\,E(Y)XX and YY independent with finite means

For uncorrelated variables the variances add for differences too, while standard deviations do not add. If XX is −1-1 or 11 with probabilities 1/41/4 and 3/43/4, then E(X)=1/2E(X) = 1/2, E(X2)=1E(X^2) = 1 and Var⁡(X)=3/4\operatorname{Var}(X) = 3/4. For an independent copy YY of XX, Var⁡(X+Y)=3/2\operatorname{Var}(X + Y) = 3/2, while Var⁡(X+X)=Var⁡(2X)=3\operatorname{Var}(X + X) = \operatorname{Var}(2X) = 3.

Lessons Discrete Random Variables and Probability Distributions, Expected Value, Variance and Sums of Random Variables

Models for counts

ModelP(X=k)P(X = k)MeanVariance
Bernoulli⁡(p)\operatorname{Bernoulli}(p)pp for k=1k = 1, 1−p1 - p for k=0k = 0ppp(1−p)p(1 - p)
Binomial⁡(n,p)\operatorname{Binomial}(n, p)(nk)pk(1−p)n−k\dbinom{n}{k} p^k (1 - p)^{n - k} for k=0,…,nk = 0, \dots, nnpnpnp(1−p)np(1 - p)
Hypergeometric(Kk)(N−Kn−k)(Nn)\dfrac{\binom{K}{k}\binom{N - K}{n - k}}{\binom{N}{n}}nKNn\dfrac{K}{N}nKN(1−KN)N−nN−1n\dfrac{K}{N}\left(1 - \dfrac{K}{N}\right)\dfrac{N - n}{N - 1}
Poisson⁡(λ)\operatorname{Poisson}(\lambda)e−λλkk!\dfrac{e^{-\lambda}\lambda^k}{k!} for k=0,1,2,…k = 0, 1, 2, \dotsλ\lambdaλ\lambda

Each model needs its setting.

  • Binomial. The number of successes in nn independent trials, with nn fixed in advance and the same success probability pp in every trial.
  • Hypergeometric. The number of marked items in a uniformly random sample of nn drawn without replacement from NN items, KK of them marked. Its possible values are the whole numbers from max⁡(0,n−N+K)\max(0, n - N + K) to min⁡(n,K)\min(n, K), and the variance formula needs N≥2N \ge 2. When nn is a small fraction of NN it is close to Binomial⁡(n,K/N)\operatorname{Binomial}(n, K/N).
  • Poisson. The number of events that occur one at a time, independently in nonoverlapping intervals, at a constant rate rr, counted over an exposure tt, so that λ=rt\lambda = rt is an expected count, not a rate. Counts whose variance clearly exceeds their mean are overdispersed relative to this model.

For X∼Binomial⁡(4,0.2)X \sim \operatorname{Binomial}(4, 0.2), P(X=2)=6(0.2)2(0.8)2=0.1536P(X = 2) = 6(0.2)^2(0.8)^2 = 0.1536. With r=0.3r = 0.3 events per minute over 10 minutes, λ=3\lambda = 3, P(X=0)=e−3≈0.0498P(X = 0) = e^{-3} \approx 0.0498 and P(X=2)=4.5e−3≈0.224P(X = 2) = 4.5e^{-3} \approx 0.224.

Lessons Bernoulli, Binomial and Hypergeometric Models, Poisson Models for Event Counts

Continuous distributions

A continuous random variable has a density ff with f(x)≥0f(x) \ge 0 and total area 11 under its graph, and probabilities are areas, so for a≤ba \le b

P(a≤X≤b)=∫abf(x) dx=F(b)−F(a).\begin{aligned} &P(a \le X \le b) \\[0.4em] &\quad = \int_a^b f(x)\,dx \\[0.4em] &\quad = F(b) - F(a). \end{aligned}

Each single value has probability 00, so << and ≤\le give the same probabilities. A density value is not a probability and can exceed 11, and its units are the reciprocal of the units of XX.

ModelDensityMeanVariance
Uniform on [a,b][a, b] with a<ba < b1b−a\dfrac{1}{b - a} for a≤x≤ba \le x \le ba+b2\dfrac{a + b}{2}(b−a)212\dfrac{(b - a)^2}{12}
Exponential with rate r>0r > 0re−rtre^{-rt} for t≥0t \ge 01r\dfrac{1}{r}1r2\dfrac{1}{r^2}

An exponential waiting time TT has survival probability P(T>t)=e−rtP(T > t) = e^{-rt} for t≥0t \ge 0. It is the wait for the first event of a Poisson process with rate rr, and it is memoryless, P(T>s+t∣T>s)=P(T>t)P(T > s + t \mid T > s) = P(T > t) for all s,t≥0s, t \ge 0. With r=0.5r = 0.5 per minute, P(2<T≤4)=e−1−e−2≈0.2325P(2 < T \le 4) = e^{-1} - e^{-2} \approx 0.2325 and P(T>6∣T>2)=e−2≈0.1353P(T > 6 \mid T > 2) = e^{-2} \approx 0.1353.

Lessons Continuous Distributions, Density and Cumulative Probability

Normal distributions and quantiles

The normal distribution N(μ,σ2)N(\mu, \sigma^2) with σ>0\sigma > 0 has the density

f(x)=1σ2π e−(x−μ)2/(2σ2),f(x) = \frac{1}{\sigma\sqrt{2\pi}}\, e^{-(x - \mu)^2/(2\sigma^2)},

which is symmetric about μ\mu with inflection points at μ±σ\mu \pm \sigma. If X∼N(μ,σ2)X \sim N(\mu, \sigma^2), then Z=(X−μ)/σ∼N(0,1)Z = (X - \mu)/\sigma \sim N(0, 1), so

P(X≤x)=Φ ⁣(x−μσ),xq=μ+σzq.\begin{gathered} P(X \le x) = \Phi\!\left(\frac{x - \mu}{\sigma}\right), \\[0.4em] x_q = \mu + \sigma z_q . \end{gathered}

If XX is normal and b≠0b \ne 0, then a+bXa + bX is normal, and a sum of independent normal variables is normal.

qq0.900.900.950.950.9750.9750.9950.995
zqz_q1.28161.28161.64491.64491.96001.96002.57582.5758

For every normal distribution the probabilities within 1, 2 and 3 standard deviations of the mean are about 0.68270.6827, 0.95450.9545 and 0.99730.9973. This empirical rule describes the normal model, and for other shapes it can be far off. For X∼N(100,102)X \sim N(100, 10^2), P(X>120)=1−Φ(2)≈0.0228P(X > 120) = 1 - \Phi(2) \approx 0.0228 and the 0.950.95 quantile is 100+10⋅1.6449≈116.45100 + 10 \cdot 1.6449 \approx 116.45.

Lessons Normal Distributions and Quantiles

Normal approximations and their limits

For X∼Binomial⁡(n,p)X \sim \operatorname{Binomial}(n, p) with 0<p<10 < p < 1, the normal approximation replaces XX by Y∼N(np, np(1−p))Y \sim N\big(np,\ np(1 - p)\big), and the continuity correction treats each whole number kk as the interval from k−0.5k - 0.5 to k+0.5k + 0.5.

Exact probabilityApproximation
P(X≤k)P(X \le k)P(Y≤k+0.5)P(Y \le k + 0.5)
P(X≥k)P(X \ge k)P(Y≥k−0.5)P(Y \ge k - 0.5)
P(X=k)P(X = k)P(k−0.5≤Y≤k+0.5)P(k - 0.5 \le Y \le k + 0.5)

The success-failure condition asks for np≥10np \ge 10 and n(1−p)≥10n(1 - p) \ge 10, and some texts use 5 or 15 instead. It is a rule of thumb, not a bound on the error. For n=100n = 100 and p=0.5p = 0.5 the approximation gives P(X≤50)≈Φ(0.1)≈0.5398P(X \le 50) \approx \Phi(0.1) \approx 0.5398, which matches the exact value to four decimals. For n=100n = 100 and p=0.01p = 0.01 it gives P(X≤0)≈0.3077P(X \le 0) \approx 0.3077, while the exact value is 0.99100≈0.36600.99^{100} \approx 0.3660. Near p=0p = 0 or p=1p = 1, and far in the tails, use the exact binomial probability.

Lessons Normal Approximations and Their Limits

Simulation and Monte Carlo error

A simulation generates outcomes from a fully specified probability model. To estimate a probability qq from BB independent replications, record the indicator IbI_b of the event in replication bb. The estimate and its Monte Carlo standard error are

q^=1B∑b=1BIb,MCSE⁡(q^)=q(1−q)B,\begin{gathered} \hat{q} = \frac{1}{B}\sum_{b=1}^{B} I_b, \\[0.4em] \operatorname{MCSE}(\hat{q}) = \sqrt{\frac{q(1 - q)}{B}}, \end{gathered}

with q^\hat{q} in place of qq to estimate the MCSE. It shrinks like 1/B1/\sqrt{B}, so four times as many replications halve it. When no replication shows the event, or every one does, the estimated MCSE is 00, which does not mean the estimate is exact. A run that finds the event X≥5X \ge 5 for X∼Binomial⁡(20,0.1)X \sim \operatorname{Binomial}(20, 0.1) in 420 of 10000 replications gives q^=0.042\hat{q} = 0.042 with an estimated MCSE of about 0.00200.0020, and the exact value is about 0.04320.0432. Record the model, the generator, the seed and BB so that the run can be repeated exactly. More replications reduce Monte Carlo error but leave model error, the mismatch between the model and the real process, unchanged.

Lessons Simulation and Monte Carlo Error

Sampling Distributions and Estimation

A statistic varies from sample to sample, and its sampling distribution describes how. The standard error measures that variation, the law of large numbers and the central limit theorem describe sample means in large samples, and together these ideas lead to estimators, confidence intervals and sample-size plans.

Sampling distributions and standard errors

The sampling distribution of a statistic is its distribution over repeated samples of the same size, drawn by the same design from the same population. It is a different object from the population distribution and from the distribution of the values in one sample. Its standard deviation is the standard error, which describes how much the statistic varies, while the SD of the data describes how much individual values vary.

StatisticMeanStandard errorConditions
Xˉ\bar{X}μ\muσn\dfrac{\sigma}{\sqrt{n}}nn independent observations with mean μ\mu and SD σ\sigma
Xˉ\bar{X} from a simple random sampleμ\muσnN−nN−1\dfrac{\sigma}{\sqrt{n}}\sqrt{\dfrac{N - n}{N - 1}}without replacement from N≥2N \ge 2 units, σ2\sigma^2 with divisor NN
p^\hat{p}ppp(1−p)n\sqrt{\dfrac{p(1 - p)}{n}}nn independent trials with success probability pp
XˉA−XˉB\bar{X}_A - \bar{X}_BμA−μB\mu_A - \mu_BσA2nA+σB2nB\sqrt{\dfrac{\sigma_A^2}{n_A} + \dfrac{\sigma_B^2}{n_B}}independent samples
p^A−p^B\hat{p}_A - \hat{p}_BpA−pBp_A - p_BpA(1−pA)nA+pB(1−pB)nB\sqrt{\dfrac{p_A(1 - p_A)}{n_A} + \dfrac{p_B(1 - p_B)}{n_B}}independent samples

The parameters in these formulas are usually unknown, and the estimated standard errors use ss and p^\hat{p} in their place, as in s/ns/\sqrt{n}. The factor (N−n)/(N−1)(N - n)/(N - 1) is the finite population correction for the variance, close to 11 when the sample is a small fraction of the population, and it multiplies the variance of p^\hat{p} in the same way. Quadrupling nn halves a standard error, so with σ=12\sigma = 12 the SE of the mean is 2.42.4 for n=25n = 25 and 1.21.2 for n=100n = 100.

Dependence changes the standard error. For kk independent clusters of mm observations, each with variance σ2\sigma^2 and with correlation ρ\rho between observations in the same cluster, Var⁡(Xˉ)=Dσ2/n\operatorname{Var}(\bar{X}) = D\sigma^2/n with n=kmn = km, the design effect D=1+(m−1)ρD = 1 + (m - 1)\rho and the effective sample size n/Dn/D. With 100 readings in clusters of 10, ρ=0.2\rho = 0.2 and σ=12\sigma = 12, the design effect is 2.82.8, the SE is about 2.012.01 instead of 1.21.2, and the effective sample size is about 35.735.7.

Lessons Sampling Distributions of Means and Proportions, Standard Deviation and Standard Error

The law of large numbers and the central limit theorem

Let X1,X2,…X_1, X_2, \dots be independent and identically distributed with mean μ\mu and variance σ2\sigma^2, and let Xˉn\bar{X}_n be the mean of the first nn of them.

Law of large numbers. When σ2\sigma^2 is finite, for every ε>0\varepsilon > 0 the probability P(∣Xˉn−μ∣≥ε)P(\lvert \bar{X}_n - \mu \rvert \ge \varepsilon) tends to 00 as n→∞n \to \infty, and Chebyshev’s inequality bounds it by σ2/(nε2)\sigma^2/(n\varepsilon^2). For independent and identically distributed observations a finite mean is already enough. Averages settle by dilution, not by compensation, so a run of one outcome does not make the other outcome more likely on the next trial, and expecting it to is the gambler’s fallacy.

Central limit theorem. When 0<σ2<∞0 < \sigma^2 < \infty, for every real number zz

P ⁣(Xˉn−μσ/n≤z)→Φ(z),P\!\left(\frac{\bar{X}_n - \mu}{\sigma/\sqrt{n}} \le z\right) \to \Phi(z),

as n→∞n \to \infty, so for large nn the sample mean is approximately N(μ,σ2/n)N(\mu, \sigma^2/n). For a normal population this holds exactly for every n≥1n \ge 1. No single sample size, such as 30, is enough for every population, because skewness and heavy tails slow the approach, especially for tail probabilities. Without a finite variance the theorem can fail, and the mean of independent standard Cauchy variables has the same standard Cauchy distribution for every nn.

The law of large numbers says where the mean settles, and the central limit theorem describes the shape and size of its fluctuations. Neither one describes the shape of the data in a single sample. Independent exponential waits with mean 2 minutes have SD 2 minutes, so the mean of 100 waits has SE⁡=0.2\operatorname{SE} = 0.2, and P(1.6≤Xˉ≤2.4)≈Φ(2)−Φ(−2)≈0.9545P(1.6 \le \bar{X} \le 2.4) \approx \Phi(2) - \Phi(-2) \approx 0.9545, while the exact value is about 0.95500.9550.

Lessons The Law of Large Numbers, The Central Limit Theorem

Student’s t, chi-square and F distributions

DistributionConstructionProperties
χk2\chi^2_kZ12+⋯+Zk2Z_1^2 + \cdots + Z_k^2 for independent standard normal ZiZ_inonnegative, mean kk, variance 2k2k, right-skewed
tνt_\nuZV/ν\dfrac{Z}{\sqrt{V/\nu}} with independent Z∼N(0,1)Z \sim N(0, 1) and V∼χν2V \sim \chi^2_\nusymmetric about 00, heavier tails than N(0,1)N(0, 1), close to N(0,1)N(0, 1) for large ν\nu
Fd1,d2F_{d_1, d_2}U/d1V/d2\dfrac{U/d_1}{V/d_2} with independent U∼χd12U \sim \chi^2_{d_1} and V∼χd22V \sim \chi^2_{d_2}nonnegative, right-skewed, 1/F∼Fd2,d11/F \sim F_{d_2, d_1}

If T∼tνT \sim t_\nu, then T2∼F1,νT^2 \sim F_{1,\nu}. For n≥2n \ge 2 independent observations from N(μ,σ2)N(\mu, \sigma^2), the sample mean and the sample variance are independent, and

(n−1)S2σ2∼χn−12,Xˉ−μS/n∼tn−1.\begin{gathered} \frac{(n - 1)S^2}{\sigma^2} \sim \chi^2_{n-1}, \\[0.4em] \frac{\bar{X} - \mu}{S/\sqrt{n}} \sim t_{n-1}. \end{gathered}

Degrees of freedom belong to the construction, so they are not always n−1n - 1. A critical value is a quantile used as a cutoff, such as χ0.95,12≈3.841\chi^2_{0.95,1} \approx 3.841, χ0.95,42≈9.488\chi^2_{0.95,4} \approx 9.488 and F0.95; 4,8≈3.838F_{0.95;\,4,8} \approx 3.838. The t critical values for two-sided 95 percent procedures are

ν\nu448824249999∞\infty
t0.975,νt_{0.975,\nu}2.77642.77642.30602.30602.06392.06391.98421.98421.96001.9600

Lessons Student’s t, Chi-Square and F Distributions

Estimators, bias and mean squared error

An estimator θ^\hat{\theta} is a rule that computes a value for a parameter θ\theta from the data, and an estimate is the value it gives for the data actually observed. Its properties describe its behavior over repeated samples,

Bias⁡(θ^)=E(θ^)−θ,MSE⁡(θ^)=E[(θ^−θ)2],MSE⁡=Var⁡+Bias⁡2.\begin{gathered} \operatorname{Bias}(\hat{\theta}) = E(\hat{\theta}) - \theta, \\[0.4em] \operatorname{MSE}(\hat{\theta}) = E\big[(\hat{\theta} - \theta)^2\big], \\[0.4em] \operatorname{MSE} = \operatorname{Var} + \operatorname{Bias}^2 . \end{gathered}

An estimator is unbiased when its bias is 0 for every allowed θ\theta, and consistent when it converges in probability to θ\theta as nn grows. For independent observations from one population with finite variance, Xˉ\bar{X} is unbiased for μ\mu and S2S^2 is unbiased for σ2\sigma^2, while E(S)≤σE(S) \le \sigma, so SS tends to underestimate σ\sigma. A small bias can be worth a large drop in variance. An unbiased estimator with variance 4 has MSE 4, while one with bias 1 and variance 1 has MSE 2.

Lessons Estimation, Bias, Precision and Mean Squared Error

Likelihood and maximum likelihood

For a model with parameter θ\theta and fixed observed data, the likelihood L(θ)L(\theta) is the probability of the data under θ\theta, or their density for continuous data, read as a function of θ\theta. It is not a probability distribution for θ\theta. The ratio L(θ1)/L(θ2)L(\theta_1)/L(\theta_2) compares how well two values account for the data. The maximum likelihood estimate maximizes L(θ)L(\theta), or equivalently the log-likelihood ℓ(θ)=log⁡L(θ)\ell(\theta) = \log L(\theta), and for independent observations the likelihood is a product and the log-likelihood a sum.

Six successes in eight independent Bernoulli trials give L(p)=p6(1−p)2L(p) = p^6(1 - p)^2, which is largest at p^=6/8=0.75\hat{p} = 6/8 = 0.75, and L(0.75)/L(0.5)≈2.85L(0.75)/L(0.5) \approx 2.85. With no successes the maximum is at the boundary value p^=0\hat{p} = 0, although small positive values of pp remain compatible with the data.

Lessons Likelihood and Maximum Likelihood Estimation

Confidence intervals

An interval procedure [L,U][L, U] has confidence level 1−α1 - \alpha when P(L≤θ≤U)=1−αP(L \le \theta \le U) = 1 - \alpha for every allowed value of θ\theta, with the probability taken over repeated samples while θ\theta stays fixed. Some procedures reach this only approximately, and some guarantee at least 1−α1 - \alpha. Once the data are in, a computed interval either contains θ\theta or does not, so a 95 percent confidence level describes how often the procedure captures θ\theta, not the probability that this particular interval does. Many intervals have the form estimate ±\pm critical value ×\times standard error. The margin of error, the half-width, reflects only random sampling error, not bias from selection, nonresponse or measurement.

TargetIntervalConditions
Mean, σ\sigma knownxˉ±z1−α/2 σn\bar{x} \pm z_{1-\alpha/2}\,\dfrac{\sigma}{\sqrt{n}}independent normal observations, approximate for large nn otherwise
Meanxˉ±t1−α/2, n−1 sn\bar{x} \pm t_{1-\alpha/2,\,n-1}\,\dfrac{s}{\sqrt{n}}n≥2n \ge 2 independent observations, exact for a normal population and approximate otherwise
Proportion, Waldp^±z1−α/2p^(1−p^)n\hat{p} \pm z_{1-\alpha/2}\sqrt{\dfrac{\hat{p}(1 - \hat{p})}{n}}binomial model, poor coverage for small nn or pp near 00 or 11
Proportion, Wilson[c−h, c+h][c - h,\ c + h] as belowbinomial model, endpoints always inside [0,1][0, 1]
Proportion, Clopper-Pearsonthe values of pp rejected by neither exact one-sided binomial test at level α/2\alpha/2binomial model, coverage at least 1−α1 - \alpha for every pp

The Wilson interval is the set of pp with ∣p^−p∣≤zp(1−p)/n\lvert \hat{p} - p \rvert \le z\sqrt{p(1 - p)/n}, where z=z1−α/2z = z_{1-\alpha/2}. Solving gives the center cc and half-width hh,

D=1+z2n,c=1D(p^+z22n),h=zDp^(1−p^)n+z24n2.\begin{gathered} D = 1 + \frac{z^2}{n}, \\[0.4em] c = \frac{1}{D}\left(\hat{p} + \frac{z^2}{2n}\right), \\[0.4em] h = \frac{z}{D}\sqrt{\frac{\hat{p}(1 - \hat{p})}{n} + \frac{z^2}{4n^2}} . \end{gathered}

For n=25n = 25, xˉ=24\bar{x} = 24 and s=5s = 5 minutes, the 95 percent t interval is 24±2.0639⋅1≈[21.94,26.06]24 \pm 2.0639 \cdot 1 \approx [21.94, 26.06] minutes. For 12 successes in 20 trials the 95 percent intervals are about [0.385,0.815][0.385, 0.815] by Wald, [0.387,0.781][0.387, 0.781] by Wilson and [0.361,0.809][0.361, 0.809] by Clopper-Pearson. For no successes in 10 trials the Wald interval is the single point 00, while the Wilson and Clopper-Pearson upper limits are about 0.2780.278 and 0.3080.308.

Lessons Confidence Intervals and Coverage, Confidence Intervals for a Mean, Confidence Intervals for a Proportion

Bootstrap standard errors and intervals

The nonparametric bootstrap uses the sample as a stand-in for the population. Draw BB resamples of size nn with replacement from the observed units, compute the statistic T∗T^* on each, and use

  • the standard deviation of T1∗,…,TB∗T_1^*, \dots, T_B^*, with divisor B−1B - 1, as the bootstrap standard error,
  • the mean Tˉ∗\bar{T}^* minus the observed statistic TT as the bootstrap estimate of bias,
  • the α/2\alpha/2 and 1−α/21 - \alpha/2 quantiles of the Tb∗T_b^* as the endpoints of the percentile interval.

Resample the units that were sampled independently, keeping pairs or clusters whole, and use blocks of consecutive values for a time series. The bootstrap cannot correct a biased sample, and it works poorly for very small samples and for statistics such as the sample maximum. For waits of 2, 3, 4, 5, 7 and 9 minutes, all 66=466566^6 = 46656 resamples give a bootstrap distribution of the median with standard deviation about 1.351.35 minutes and, taking each quantile as the smallest value whose cumulative probability reaches the level, a 95 percent percentile interval of [2.5,8][2.5, 8] minutes.

Lessons Bootstrap Standard Errors and Intervals

Sample size and margin of error

For a margin of error of at most EE with critical value z=z1−α/2z = z_{1-\alpha/2}, a proportion and a mean estimated from independent observations need

n≥z2 p(1−p)E2,n≥(zσE)2,\begin{gathered} n \ge \frac{z^2\,p(1 - p)}{E^2}, \\[0.4em] n \ge \left(\frac{z\sigma}{E}\right)^2, \end{gathered}

rounded up, with a planning value for pp or σ\sigma from a pilot study or earlier work. Since p(1−p)≤0.25p(1 - p) \le 0.25, the conservative choice p=0.5p = 0.5 works whatever the true pp is, and a planning SD that is too small gives a margin larger than intended. Halving EE roughly quadruples nn. Multiply by the design effect, round up at the end, and divide by the expected response rate to find how many units to invite. For E=0.05E = 0.05 at 95 percent with p=0.5p = 0.5, n≥384.16n \ge 384.16, so 385 responses are needed, a design effect of 1.51.5 raises this to 577, and an 80 percent response rate means inviting ⌈577/0.8⌉=722\lceil 577/0.8 \rceil = 722 people.

Lessons Sample Size and Margin of Error

Hypothesis Tests and Two-Group Comparisons

A hypothesis test asks whether the data are compatible with a stated null model. The p-value measures how surprising the data would be if that model were true, and it is read together with an estimate of the effect and its interval.

Hypothesis tests and p-values

  1. State H0H_0 and H1H_1 about a parameter, and fix the test statistic, the direction that counts as extreme, the significance level α\alpha and the sample size before looking at the outcome data.
  2. Find the null distribution, the distribution of the test statistic when H0H_0 and the model assumptions hold.
  3. Compute the p-value, the probability under the null model of a test statistic at least as extreme as the observed one.
  4. Reject H0H_0 when the p-value is at most α\alpha, and otherwise fail to reject it. Report the estimate and an interval along with the p-value.

A p-value is not the probability that H0H_0 is true, and one minus the p-value is not the probability that H1H_1 is true. A one-sided test counts departures in one stated direction and a two-sided test counts both. For a symmetric null distribution the two-sided p-value is twice the smaller one-sided p-value, capped at 1, and for an asymmetric null distribution the rule for the two-sided p-value must be stated. Sixteen successes in 20 trials under H0 ⁣:p=0.5H_0\colon p = 0.5 give the one-sided p-value P(X≥16)=6196/220≈0.0059P(X \ge 16) = 6196/2^{20} \approx 0.0059 and the two-sided p-value 0.01180.0118.

Lessons Hypothesis Tests and P-Values

Type I and type II errors and power

H0H_0 trueH0H_0 false
Reject H0H_0type I error, probability at most α\alphacorrect, with probability equal to the power
Fail to reject H0H_0correcttype II error, probability β\beta

The power 1−β1 - \beta is computed at a specific alternative value. For a given test it usually grows with the true effect, the sample size and α\alpha, and falls as the SD of the data grows. For the one-sided z test of H0 ⁣:μ=μ0H_0\colon \mu = \mu_0 against H1 ⁣:μ>μ0H_1\colon \mu > \mu_0 with known σ\sigma, the power at μ=μ0+δ\mu = \mu_0 + \delta and the sample size for power 1−β1 - \beta are

1−Φ ⁣(z1−α−δnσ),n≥(σ (z1−α+z1−β)δ)2.\begin{gathered} 1 - \Phi\!\left(z_{1-\alpha} - \frac{\delta\sqrt{n}}{\sigma}\right), \\[0.4em] n \ge \left(\frac{\sigma\,(z_{1-\alpha} + z_{1-\beta})}{\delta}\right)^2 . \end{gathered}

With σ=10\sigma = 10, δ=2\delta = 2, α=0.05\alpha = 0.05 and power 0.800.80, n≥154.56n \ge 154.56, so 155 observations. The minimum detectable effect is the smallest effect at which a fixed design reaches the target power. Testing again and again as data arrive and stopping at the first significant result, which is optional stopping, raises the type I error rate above α\alpha.

Lessons Type I Error, Type II Error and Power

Statistical significance and practical importance

Statistical significance says only that the data are hard to reconcile with H0H_0. The effect size, the magnitude of the effect in its units, and its interval show whether the effect matters, judged against the smallest effect that would matter in practice, fixed in advance. A very large study can make a negligible effect significant, and a small study can leave an important effect nonsignificant. Failing to reject H0H_0 is absence of evidence, not evidence that the effect is zero.

StudyEstimateSE95 percent intervalTwo-sided p-value
A0.20.20.050.05[0.10,0.30][0.10, 0.30]0.000060.00006
B3322[−0.92,6.92][-0.92, 6.92]0.1340.134

If effects below 1 unit do not matter, study A gives clear evidence of an effect that is too small to matter, and study B is inconclusive, compatible with no effect and with a large one. To show that an effect is negligible, choose an equivalence margin Δ>0\Delta > 0 in advance and check whether the 100(1−2α)100(1 - 2\alpha) percent interval lies within [−Δ,Δ][-\Delta, \Delta], which is the two one-sided tests procedure.

Lessons Statistical Significance and Practical Importance

Randomization and permutation tests

Under a sharp null hypothesis, such as no treatment effect on any unit, every unit’s response would be the same under every assignment the design could have produced. A randomization test recomputes the statistic for every assignment the design allows, and when these are equally likely its p-value is the proportion of them, the observed one included, whose statistic is at least as extreme as the observed one. A permutation test applies the same idea to rearrangements of the data that leave the null distribution unchanged, such as relabeling two independent samples from one distribution. The allowed rearrangements must match the design, for example swaps only within pairs or blocks. When there are too many to list, draw BB of them at random, count the number bb at least as extreme as the observed statistic, and report

pMC=b+1B+1,p_{\text{MC}} = \frac{b + 1}{B + 1},

which keeps the type I error rate at most α\alpha for every BB. With treated responses 4, 5 and 6 and control responses 1, 2 and 3, the difference in means is 3. Only the observed assignment and its mirror image, out of (63)=20\binom{6}{3} = 20, reach an absolute difference of 3, so the two-sided p-value is 2/20=0.102/20 = 0.10.

Lessons Randomization and Permutation Tests

Tests for means and proportions

SituationTest statisticReference
One meant=xˉ−μ0s/nt = \dfrac{\bar{x} - \mu_0}{s/\sqrt{n}}tn−1t_{n-1}
Paired data with differences did_it=dˉ−μ0sd/nt = \dfrac{\bar{d} - \mu_0}{s_d/\sqrt{n}}tn−1t_{n-1} for nn pairs
Two independent means, Welcht=xˉA−xˉB−Δ0sA2/nA+sB2/nBt = \dfrac{\bar{x}_A - \bar{x}_B - \Delta_0}{\sqrt{s_A^2/n_A + s_B^2/n_B}}tνt_\nu with the Welch-Satterthwaite ν\nu
One proportionz=p^−p0p0(1−p0)/nz = \dfrac{\hat{p} - p_0}{\sqrt{p_0(1 - p_0)/n}}N(0,1)N(0, 1)
Two proportionsz=p^A−p^Bp^(1−p^)(1/nA+1/nB)z = \dfrac{\hat{p}_A - \hat{p}_B}{\sqrt{\hat{p}(1 - \hat{p})(1/n_A + 1/n_B)}} with pooled p^=xA+xBnA+nB\hat{p} = \dfrac{x_A + x_B}{n_A + n_B}N(0,1)N(0, 1)

Means. The t tests need independent observations, or independent pairs, and a sample mean that is close to normal, which holds exactly for a normal population and approximately for larger samples without strong skewness or outliers. Paired data are analyzed through the within-pair differences, never as two independent samples. Welch’s test does not assume equal variances, and its degrees of freedom are

ν=(vA+vB)2vA2nA−1+vB2nB−1,vA=sA2nA,vB=sB2nB.\begin{gathered} \nu = \frac{(v_A + v_B)^2}{\dfrac{v_A^2}{n_A - 1} + \dfrac{v_B^2}{n_B - 1}}, \\[0.4em] v_A = \frac{s_A^2}{n_A}, \quad v_B = \frac{s_B^2}{n_B}. \end{gathered}

The pooled two-sample t test assumes equal population variances and uses sp2=[(nA−1)sA2+(nB−1)sB2]/(nA+nB−2)s_p^2 = \big[(n_A - 1)s_A^2 + (n_B - 1)s_B^2\big]/(n_A + n_B - 2) with nA+nB−2n_A + n_B - 2 degrees of freedom.

Proportions. The z tests need independent trials with a common success probability in each group, and expected counts of successes and failures under H0H_0, such as np0np_0 and n(1−p0)n(1 - p_0), of at least about 5 to 10. Otherwise use the exact binomial test for one proportion or Fisher’s exact test for two.

Tests and intervals. Each t test has a matching interval, estimate ± t1−α/2, ν×SE⁡^\pm\, t_{1-\alpha/2,\,\nu} \times \widehat{\operatorname{SE}}, and the two-sided test at level α\alpha rejects exactly when the null value is not strictly inside that 1−α1 - \alpha interval. The interval for pA−pBp_A - p_B uses the unpooled standard error p^A(1−p^A)/nA+p^B(1−p^B)/nB\sqrt{\hat{p}_A(1 - \hat{p}_A)/n_A + \hat{p}_B(1 - \hat{p}_B)/n_B}, and the one-proportion test puts p0p_0 in its standard error, so for proportions the match between test and interval is only approximate. The standardized mean difference d=(xˉ−μ0)/sd = (\bar{x} - \mu_0)/s gives the effect in SD units, and t=dnt = d\sqrt{n}.

Group A with n=20n = 20, mean 18 and SD 4 and group B with n=30n = 30, mean 22 and SD 6 give SE⁡^=0.8+1.2≈1.414\widehat{\operatorname{SE}} = \sqrt{0.8 + 1.2} \approx 1.414, t≈−2.83t \approx -2.83 and ν≈48.0\nu \approx 48.0, a two-sided p-value of about 0.00680.0068 and the 95 percent interval of about [−6.84,−1.16][-6.84, -1.16] for μA−μB\mu_A - \mu_B. With 60 of 100 successes against 45 of 100, the pooled proportion is 0.5250.525, z≈2.12z \approx 2.12, the two-sided p-value is about 0.0340.034, and the 95 percent interval for pA−pBp_A - p_B is about [0.013,0.287][0.013, 0.287].

Lessons One-Sample t-Tests, One-Proportion Tests, Comparing Two Independent Means, Paired t-Tests and Before-After Data, Comparing Two Proportions

Rank-based tests

TestDataNull hypothesisStatistic
Sign testpaired differences did_i, or xi−m0x_i - m_0 for one sampleP(D>0)=P(D<0)P(D > 0) = P(D < 0)the number KK of positive values among the mm nonzero ones, Binomial⁡(m,12)\operatorname{Binomial}(m, \tfrac12) under H0H_0 given mm
Wilcoxon signed-rankpaired differences did_ithe distribution of DD is symmetric about 00W+W_+, the sum of the ranks of the ∣di∣\lvert d_i \rvert over the positive did_i
Wilcoxon rank-sum or Mann-Whitneytwo independent samplesFA=FBF_A = F_Bthe rank sum RAR_A of sample A in the pooled ranking, or UA=RA−12nA(nA+1)U_A = R_A - \tfrac12 n_A(n_A + 1)

Without ties, with mm nonzero differences and N=nA+nBN = n_A + n_B, the null means and variances are

E0(W+)=m(m+1)4,Var⁡0(W+)=m(m+1)4×2m+16,E0(UA)=nAnB2,Var⁡0(UA)=nAnB(N+1)12.\begin{aligned} E_0(W_+) &= \frac{m(m + 1)}{4}, \\[0.4em] \operatorname{Var}_0(W_+) &= \frac{m(m + 1)}{4} \\[0.2em] &\quad \times \frac{2m + 1}{6}, \\[0.4em] E_0(U_A) &= \frac{n_A n_B}{2}, \\[0.4em] \operatorname{Var}_0(U_A) &= \frac{n_A n_B (N + 1)}{12}. \end{aligned}

In the usual versions zero differences are dropped, and tied values get the average of their ranks, which changes the exact null distribution and lowers the variance. The ratio θ^=UA/(nAnB)\hat{\theta} = U_A/(n_A n_B) estimates the probability of superiority θ=P(X>Y)+12P(X=Y)\theta = P(X > Y) + \tfrac12 P(X = Y) for independent draws XX from A and YY from B. For continuous differences the sign test is a test that the median of DD is 0. The signed-rank test is a test about the median only under the added assumption of symmetry, and the rank-sum test compares medians only under a location-shift model FA(x)=FB(x−δ)F_A(x) = F_B(x - \delta).

For A=(1,3,5)A = (1, 3, 5) and B=(2,4,6)B = (2, 4, 6), RA=9R_A = 9, UA=3U_A = 3 and θ^=1/3\hat{\theta} = 1/3. Of the 20 equally likely ways to choose which three values carry the label A, 14 give ∣UA−4.5∣≥1.5\lvert U_A - 4.5 \rvert \ge 1.5, so the exact two-sided p-value is 0.700.70.

Lessons Sign Tests and Wilcoxon Signed-Rank Tests, Mann-Whitney Tests and Rank-Based Comparisons

Categorical Data Inference

Categorical outcomes are summarized by counts, proportions, risks and odds. Chi-square tests compare observed counts with the counts a model expects, exact tests handle small counts, and paired yes or no data need a test of their own.

Risk, odds and relative effects

Take a 2 by 2 table with aa outcomes and bb non-outcomes among the nAn_A members of group A, and cc outcomes and dd non-outcomes among the nBn_B members of the reference group B, with risks pAp_A and pBp_B.

MeasureDefinitionEstimateNo difference
Risk differencepA−pBp_A - p_BanA−cnB\dfrac{a}{n_A} - \dfrac{c}{n_B}00
Risk ratiopApB\dfrac{p_A}{p_B}a/nAc/nB\dfrac{a/n_A}{c/n_B}11
Odds ratiopA/(1−pA)pB/(1−pB)\dfrac{p_A/(1 - p_A)}{p_B/(1 - p_B)}adbc\dfrac{ad}{bc}11

The odds of an outcome with probability p<1p < 1 are o=p/(1−p)o = p/(1 - p), and p=o/(1+o)p = o/(1 + o). For risks strictly between 0 and 1 with pA>pBp_A > p_B, the odds ratio exceeds the risk ratio, which exceeds 1. The gap between them is small when both risks are small and can be large for a common outcome. A relative effect needs its baseline risk, since doubling a risk of 0.010.01 adds 1 percentage point while doubling a risk of 0.200.20 adds 20. A case-control study fixes the numbers of cases and controls, so it estimates the odds ratio ad/(bc)ad/(bc) but not risks, risk differences or risk ratios.

Intervals for ratios are built on the log scale. With all four counts positive,

SE⁡(log⁡RR^)≈1a−1nA+1c−1nB,SE⁡(log⁡OR^)≈1a+1b+1c+1d,\begin{aligned} &\operatorname{SE}(\log \widehat{\text{RR}}) \\[0.4em] &\quad \approx \sqrt{\frac{1}{a} - \frac{1}{n_A} + \frac{1}{c} - \frac{1}{n_B}}, \\[0.4em] &\operatorname{SE}(\log \widehat{\text{OR}}) \\[0.4em] &\quad \approx \sqrt{\frac{1}{a} + \frac{1}{b} + \frac{1}{c} + \frac{1}{d}}, \end{aligned}

and the interval for the risk ratio is RR^ e±z1−α/2SE⁡\widehat{\text{RR}}\,e^{\pm z_{1-\alpha/2}\operatorname{SE}}, with the same form for the odds ratio. With 20 of 100 people in group A and 10 of 100 in group B having the outcome, the risk difference is 0.100.10, the risk ratio is 2 and the odds ratio is (20⋅90)/(80⋅10)=2.25(20 \cdot 90)/(80 \cdot 10) = 2.25, and the 95 percent interval for the risk ratio is about [0.99,4.05][0.99, 4.05].

Lessons Risk, Odds and Relative Effects

Chi-square tests

Every chi-square test compares observed counts OO with the counts EE expected under H0H_0,

X2=∑(O−E)2E,X^2 = \sum \frac{(O - E)^2}{E},

and the approximate p-value is the upper tail P(χν2≥X2)P(\chi^2_\nu \ge X^2).

TestDataH0H_0Expected countDegrees of freedom
Goodness of fitone sample in kk categoriesthe category probabilities are p10,…,pk0p_{10}, \dots, p_{k0}, fixed in advancenpi0np_{i0}k−1k - 1, minus one for each parameter estimated from the counts by maximum likelihood
Independenceone sample classified by two variablesthe two variables are independentrow total×column totaln\dfrac{\text{row total} \times \text{column total}}{n}(r−1)(c−1)(r - 1)(c - 1) for rr rows and cc columns
Homogeneityindependent samples from several groupsevery group has the same distribution over the categoriesas for independence(r−1)(c−1)(r - 1)(c - 1)

The approximation needs independent observations, raw counts rather than percentages, and large expected counts, commonly all at least 5. A Pearson residual (O−E)/E(O - E)/\sqrt{E} shows which cells drive a large X2X^2, and Cramér’s V,

V=X2n min⁡(r−1, c−1),V = \sqrt{\frac{X^2}{n\,\min(r - 1,\ c - 1)}},

measures the strength of association on a scale from 0 to 1. Counts of 28, 22, 18 and 12 tested against four equal probabilities have every E=20E = 20, X2=6.8X^2 = 6.8 on 3 degrees of freedom and p≈0.079p \approx 0.079. A 2 by 2 table with counts 30, 20, 20 and 30 has every E=25E = 25, X2=4X^2 = 4 on 1 degree of freedom, p≈0.0455p \approx 0.0455 and V=0.2V = 0.2.

Lessons Chi-Square Goodness-of-Fit Tests, Chi-Square Independence and Homogeneity

Fisher’s exact test and McNemar’s test

For a 2 by 2 table of independent units, Fisher’s exact test conditions on both margins. With first row total nAn_A, first column total mm and grand total NN, the count XX in the top left cell has, under H0H_0, the hypergeometric distribution

P(X=x∣margins)=(mx)(N−mnA−x)(NnA).\begin{aligned} &P(X = x \mid \text{margins}) \\[0.4em] &\quad = \frac{\binom{m}{x}\binom{N - m}{n_A - x}}{\binom{N}{n_A}} . \end{aligned}

The common two-sided p-value adds the probabilities of all tables with these margins that are no more probable than the observed table. Because the distribution is discrete, the type I error rate of the test is at most α\alpha and often below it. The table with rows (4,0)(4, 0) and (0,4)(0, 4) has two-sided p-value 2/70≈0.0292/70 \approx 0.029.

For paired binary data from independent pairs, such as different people each answering the same yes or no question twice, only the discordant pairs carry information about a change. With bb pairs that answer yes and then no, and cc pairs that answer no and then yes, McNemar’s test of equal yes proportions at the two times uses the fact that, given b+cb + c discordant pairs, the count BB of the first kind is Binomial⁡(b+c,12)\operatorname{Binomial}(b + c, \tfrac12) under H0H_0. Its exact two-sided p-value is min⁡(1, 2P(B≤min⁡(b,c)))\min\big(1,\ 2P(B \le \min(b, c))\big), and with many discordant pairs X2=(b−c)2/(b+c)X^2 = (b - c)^2/(b + c) is compared with χ12\chi^2_1. The second yes proportion minus the first is (c−b)/n(c - b)/n. With b=1b = 1 and c=7c = 7 the exact p-value is 2⋅9/256≈0.0702 \cdot 9/256 \approx 0.070.

Lessons Sparse Tables, Fisher’s Exact Test and Paired Binary Data

Several Groups and Variability

With several groups, one overall test asks whether any differences exist, follow-up comparisons say which, and multiplicity control keeps the error rate of the whole family of comparisons in check. Factorial designs study several factors at once, and the spread of a variable can itself be the target of inference.

One-way ANOVA

For kk groups with njn_j observations yijy_{ij} in group jj, group means yˉj\bar{y}_j, grand mean yˉ\bar{y} and NN observations in all,

SourceSum of squaresDegrees of freedomMean square
Between groupsSSB=∑jnj(yˉj−yˉ)2\text{SS}_B = \sum_j n_j(\bar{y}_j - \bar{y})^2k−1k - 1MSB=SSBk−1\text{MS}_B = \dfrac{\text{SS}_B}{k - 1}
Within groupsSSW=∑j∑i(yij−yˉj)2\text{SS}_W = \sum_j \sum_i (y_{ij} - \bar{y}_j)^2N−kN - kMSW=SSWN−k\text{MS}_W = \dfrac{\text{SS}_W}{N - k}
TotalSST=SSB+SSW\text{SS}_T = \text{SS}_B + \text{SS}_WN−1N - 1

The test of H0 ⁣:μ1=⋯=μkH_0\colon \mu_1 = \cdots = \mu_k uses F=MSB/MSWF = \text{MS}_B/\text{MS}_W, which has the Fk−1, N−kF_{k-1,\,N-k} distribution under H0H_0 when the observations are independent and each group is normal with the same variance. The F test tolerates moderate nonnormality, especially with similar group sizes that are not very small. Unequal variances matter most when the group sizes differ, and Welch’s ANOVA drops the equal-variance assumption. A rejection says that the means are not all equal, not which ones differ. The groups (2,4,6)(2, 4, 6), (4,6,8)(4, 6, 8) and (6,8,10)(6, 8, 10) have SSB=SSW=24\text{SS}_B = \text{SS}_W = 24, F=12/4=3F = 12/4 = 3 on 2 and 6 degrees of freedom and p=0.125p = 0.125.

Lessons One-Way ANOVA and Welch ANOVA

Factorial designs, blocking and interactions

A factorial design runs every combination of the levels of its factors, and a cell mean is the mean response at one combination. For two factors A and B at two levels each, with these cell means,

B0B_0B1B_1Simple effect of B
A0A_01010121222
A1A_11414202066

the interaction is the difference of the simple effects, 6−2=46 - 2 = 4, and it is zero exactly when the effect of B is the same at both levels of A. A main effect averages simple effects over the other factor, so the main effect of B is (2+6)/2=4(2 + 6)/2 = 4 and that of A is (14+20)/2−(10+12)/2=6(14 + 20)/2 - (10 + 12)/2 = 6. When the interaction is large, report the simple effects, because a main effect averages effects that differ. Replication, more than one experimental unit per cell, is needed to separate the effects from random error. In a randomized block design the treatments are randomized separately within blocks of similar units, and the analysis keeps the blocks.

Lessons Factorial Designs, Blocking and Interactions

Contrasts and multiple testing

A contrast is L=∑jcjμjL = \sum_j c_j\mu_j with ∑jcj=0\sum_j c_j = 0. In one-way ANOVA it is estimated by L^=∑jcjyˉj\hat{L} = \sum_j c_j\bar{y}_j with standard error MSW∑jcj2/nj\sqrt{\text{MS}_W\sum_j c_j^2/n_j} and tested against tN−kt_{N-k}. Running mm tests of true null hypotheses, each at level α\alpha, raises the chance of at least one false rejection, to 1−(1−α)m1 - (1 - \alpha)^m for independent tests, which is about 0.640.64 for m=20m = 20 and α=0.05\alpha = 0.05. The family-wise error rate is the probability of at least one false rejection, and the false discovery rate is the expected share of false rejections among all rejections, counted as 0 when nothing is rejected.

MethodRule for ordered p-values p(1)≤⋯≤p(m)p_{(1)} \le \cdots \le p_{(m)}Controls
Bonferronireject HiH_i when pi≤α/mp_i \le \alpha/mthe family-wise error rate, under any dependence
Holmreject H(1),H(2),…H_{(1)}, H_{(2)}, \dots in order while p(i)≤αm−i+1p_{(i)} \le \dfrac{\alpha}{m - i + 1}, and stop at the first failurethe family-wise error rate, under any dependence, rejecting everything Bonferroni rejects
Tukeyintervals yˉi−yˉj±q2MSW(1ni+1nj)\bar{y}_i - \bar{y}_j \pm \dfrac{q}{\sqrt{2}}\sqrt{\text{MS}_W\left(\dfrac{1}{n_i} + \dfrac{1}{n_j}\right)}, with qq the 1−α1 - \alpha quantile of the studentized range for kk means and N−kN - k degrees of freedomthe family-wise error rate for all pairwise comparisons of means, for normal groups with equal variances
Benjamini-Hochbergfind the largest ii with p(i)≤imαp_{(i)} \le \dfrac{i}{m}\alpha and reject H(1),…,H(i)H_{(1)}, \dots, H_{(i)}the false discovery rate at level α\alpha, for independent or positively dependent tests

Comparisons planned before seeing the data form a smaller family than every comparison that might be chosen after looking, and post-hoc comparisons must be adjusted for every comparison that could have been made. For p-values 0.010.01, 0.030.03 and 0.200.20 at α=0.05\alpha = 0.05, Bonferroni and Holm reject only the first, since 0.030.03 exceeds both 0.05/30.05/3 and 0.05/20.05/2, while Benjamini-Hochberg rejects the first two, since 0.03≤2(0.05)/30.03 \le 2(0.05)/3.

Lessons Planned Contrasts, Post-Hoc Comparisons and Multiple Testing

Kruskal-Wallis test

Rank all NN observations of kk independent groups together, with midranks for ties, and let RjR_j be the rank sum of group jj, which has njn_j observations. The Kruskal-Wallis statistic is

H=12N(N+1)∑j=1kRj2nj−3(N+1),\begin{aligned} H &= \frac{12}{N(N + 1)}\sum_{j=1}^{k}\frac{R_j^2}{n_j} \\[0.4em] &\quad - 3(N + 1), \end{aligned}

and it tests H0 ⁣:F1=⋯=FkH_0\colon F_1 = \cdots = F_k, that all groups come from one distribution, with large values of HH as evidence against it. For large groups HH is approximately χk−12\chi^2_{k-1} under H0H_0, small groups use the exact permutation distribution, and with ties HH is divided by C=1−∑(t3−t)/(N3−N)C = 1 - \sum (t^3 - t)/(N^3 - N), where each tt is the size of a set of tied values. A rejection says that the distributions are not all identical. Reading it as a difference in medians needs further assumptions, such as distributions of the same shape. For the groups (1,2,3)(1, 2, 3), (4,5,6)(4, 5, 6) and (7,8,9)(7, 8, 9), H=7.2H = 7.2, the chi-square approximation gives p≈0.027p \approx 0.027, and the exact p-value is 6/1680≈0.00366/1680 \approx 0.0036.

Lessons Kruskal-Wallis Tests and Comparing Several Distributions

Inference for variance and comparing spread

For n≥2n \ge 2 independent observations from a normal population, (n−1)S2/σ2∼χn−12(n - 1)S^2/\sigma^2 \sim \chi^2_{n-1}, and the 1−α1 - \alpha confidence interval for σ2\sigma^2 is [L,U][L, U] with

L=(n−1)s2χ1−α/2, n−12,U=(n−1)s2χα/2, n−12.\begin{gathered} L = \frac{(n - 1)s^2}{\chi^2_{1-\alpha/2,\,n-1}}, \\[0.4em] U = \frac{(n - 1)s^2}{\chi^2_{\alpha/2,\,n-1}} . \end{gathered}

Square roots of the endpoints give an interval for σ\sigma. Five observations with s2=2.5s^2 = 2.5 give about [0.897,20.6][0.897, 20.6] for σ2\sigma^2 and [0.947,4.54][0.947, 4.54] for σ\sigma. For two independent normal samples, F=sA2/sB2F = s_A^2/s_B^2 is compared with FnA−1, nB−1F_{n_A - 1,\, n_B - 1} to test σA=σB\sigma_A = \sigma_B. Both procedures are very sensitive to nonnormality, even in large samples. Levene’s test, a one-way ANOVA on the absolute deviations from the group means, and the Brown-Forsythe version, which uses deviations from the group medians, are much less sensitive.

Lessons Inference for Variance and Comparing Spread

Regression and Prediction

Regression describes how the mean of a response changes with one or more predictors. Least squares fits the model, residual plots check it, and intervals and tests describe its uncertainty. A coefficient describes an association adjusted for the other predictors in the model, and it is a causal effect only when the design supports that. Predictions are judged on data not used to fit them.

Least squares and R-squared

For nn pairs with at least two distinct xx values, the least-squares line y^=b0+b1x\hat{y} = b_0 + b_1x minimizes SSE=∑(yi−y^i)2\text{SSE} = \sum (y_i - \hat{y}_i)^2 and has

b1=SxySxx=r sysx,b0=yˉ−b1xˉ,\begin{gathered} b_1 = \frac{S_{xy}}{S_{xx}} = r\,\frac{s_y}{s_x}, \\[0.4em] b_0 = \bar{y} - b_1\bar{x}, \end{gathered}

where Sxx=∑(xi−xˉ)2S_{xx} = \sum (x_i - \bar{x})^2 and Sxy=∑(xi−xˉ)(yi−yˉ)S_{xy} = \sum (x_i - \bar{x})(y_i - \bar{y}), and the form with rr needs sy>0s_y > 0. The line passes through (xˉ,yˉ)(\bar{x}, \bar{y}), and the residuals ei=yi−y^ie_i = y_i - \hat{y}_i add to 0. The slope is the change in the fitted value per unit of xx, in response units per predictor unit, and it compares individuals with different xx values rather than describing what happens when one individual’s xx changes. Regressing xx on yy gives a different line unless ∣r∣=1\lvert r \rvert = 1.

With SST=∑(yi−yˉ)2>0\text{SST} = \sum (y_i - \bar{y})^2 > 0,

R2=1−SSESSTR^2 = 1 - \frac{\text{SSE}}{\text{SST}}

is the share of the variation of yy around its mean that the line accounts for. In simple regression with an intercept, 0≤R2≤10 \le R^2 \le 1 and R2=r2R^2 = r^2. A high R2R^2 does not show that a line is the right form, that the relationship is causal, or that predictions outside the data will be good. The points (1,2)(1, 2), (2,3)(2, 3) and (3,5)(3, 5) give b1=1.5b_1 = 1.5, b0=1/3b_0 = 1/3, SSE=1/6\text{SSE} = 1/6, SST=14/3\text{SST} = 14/3 and R2=27/28≈0.964R^2 = 27/28 \approx 0.964.

Lessons Least Squares and R-Squared

Regression assumptions, residuals and influence

Classical inference for a line uses the model Yi=β0+β1xi+εiY_i = \beta_0 + \beta_1x_i + \varepsilon_i with these assumptions.

AssumptionStatementCheck
Linear meanE(εi∣xi)=0E(\varepsilon_i \mid x_i) = 0, so E(Y∣x)=β0+β1xE(Y \mid x) = \beta_0 + \beta_1xno curve in the plot of residuals against xx or y^\hat{y}
Constant varianceVar⁡(εi∣xi)=σ2\operatorname{Var}(\varepsilon_i \mid x_i) = \sigma^2 for every xxno fan shape in the residual plot
Independent errorsthe errors of different observations are unrelatedthe design, and residuals plotted in time or group order
Normal errorsεi∼N(0,σ2)\varepsilon_i \sim N(0, \sigma^2), needed for exact small-sample t and F inferencea normal Q-Q plot of the residuals

Normality concerns the errors around the line, not the distribution of xx or of all the yy values together. For a line, the hat value

hi=1n+(xi−xˉ)2Sxx,h_i = \frac{1}{n} + \frac{(x_i - \bar{x})^2}{S_{xx}},

also called the leverage of an observation, depends only on the predictor values, with 1/n≤hi≤11/n \le h_i \le 1 and ∑hi=2\sum h_i = 2. Cook’s distance measures how much all the fitted values move when observation ii is left out, and it combines the residual with the hat value,

Di=ei2p s2⋅hi(1−hi)2,D_i = \frac{e_i^2}{p\,s^2} \cdot \frac{h_i}{(1 - h_i)^2},

for an observation with hi<1h_i < 1 in a fit with pp coefficients, p=2p = 2 for a line, and s2=SSE/(n−p)s^2 = \text{SSE}/(n - p). Values near or above 1, or far above the rest, deserve a closer look. A high-leverage point with a large residual can move the line a lot, and an influential point is a reason to check the data and the model, not to delete the point automatically.

Lessons Regression Assumptions, Residuals and Influence

Inference for the slope and intervals for predictions

Under the model with independent normal errors of constant variance, n≥3n \ge 3 and at least two distinct xx values,

s=SSEn−2,SE⁡(b1)=sSxx,\begin{gathered} s = \sqrt{\frac{\text{SSE}}{n - 2}}, \\[0.4em] \operatorname{SE}(b_1) = \frac{s}{\sqrt{S_{xx}}}, \end{gathered}

and (b1−β1)/SE⁡(b1)∼tn−2(b_1 - \beta_1)/\operatorname{SE}(b_1) \sim t_{n-2}. The confidence interval for the slope is b1±t1−α/2, n−2SE⁡(b1)b_1 \pm t_{1-\alpha/2,\,n-2}\operatorname{SE}(b_1), and H0 ⁣:β1=0H_0\colon \beta_1 = 0 is tested with t=b1/SE⁡(b1)t = b_1/\operatorname{SE}(b_1). The slope is estimated more precisely when the residual SD is small, nn is large and the xx values are spread out. At a predictor value x0x_0, with y^0=b0+b1x0\hat{y}_0 = b_0 + b_1x_0 and

h0=1n+(x0−xˉ)2Sxx,h_0 = \frac{1}{n} + \frac{(x_0 - \bar{x})^2}{S_{xx}},

the intervals are

Target1−α1 - \alpha interval
Mean response β0+β1x0\beta_0 + \beta_1x_0y^0±t1−α/2, n−2 sh0\hat{y}_0 \pm t_{1-\alpha/2,\,n-2}\, s\sqrt{h_0}
One new observation at x0x_0y^0±t1−α/2, n−2 s1+h0\hat{y}_0 \pm t_{1-\alpha/2,\,n-2}\, s\sqrt{1 + h_0}

The prediction interval is wider because a new observation has its own error, and unlike the confidence interval it does not shrink toward zero width as nn grows. Both widen as x0x_0 moves away from xˉ\bar{x}. Extrapolation beyond the range of the data assumes that the model still holds there, which the data cannot check. For the six points with x=0,1,…,5x = 0, 1, \dots, 5, fitted line y^=1+2x\hat{y} = 1 + 2x, s=1s = 1 and Sxx=17.5S_{xx} = 17.5, the slope has SE⁡(b1)≈0.239\operatorname{SE}(b_1) \approx 0.239 and 95 percent interval about [1.34,2.66][1.34, 2.66]. At x0=2.5x_0 = 2.5 the interval for the mean response is about [4.87,7.13][4.87, 7.13], while the prediction interval is about [3.00,9.00][3.00, 9.00].

Lessons Inference for a Regression Slope, Confidence and Prediction Intervals

Multiple regression, categorical predictors and interactions

The multiple regression model E(Y∣x1,…,xk)=β0+β1x1+⋯+βkxkE(Y \mid x_1, \dots, x_k) = \beta_0 + \beta_1x_1 + \cdots + \beta_kx_k is fitted by least squares. The coefficient βj\beta_j is the difference in mean response for a one-unit difference in xjx_j with the other predictors held fixed, an adjusted association. It can differ in size and even in sign from the slope in a simple regression, and it is a causal effect only when the design supports that. Leaving out a variable that is related both to a predictor and to the response, an omitted variable, can distort the coefficients of the predictors that remain.

A categorical predictor with gg levels enters through g−1g - 1 indicator variables, and each of their coefficients compares one level with the reference level. Including indicators for all gg levels together with an intercept makes the coefficients not identifiable. An interaction term lets the effect of one predictor depend on another. In y^=10+2x+3g−xg\hat{y} = 10 + 2x + 3g - xg with an indicator gg, the reference group g=0g = 0 has y^=10+2x\hat{y} = 10 + 2x and the other group has y^=13+x\hat{y} = 13 + x, so the group difference 3−x3 - x is 3 at x=0x = 0, zero at x=3x = 3 and negative beyond. The coefficient of gg is the group difference at x=0x = 0 only. A model with an interaction usually keeps the terms it is built from, which is the hierarchy principle.

Lessons Multiple Regression and Adjusted Associations, Categorical Predictors and Interactions

Curved relationships and comparing models

A model is linear in the coefficients when its mean is a weighted sum of known functions of the predictors, such as β0+β1x+β2x2\beta_0 + \beta_1x + \beta_2x^2, or β0+β1log⁡x\beta_0 + \beta_1\log x for x>0x > 0, so least squares and the usual inference apply to it. In a polynomial the effect of a one-unit step depends on where the step starts.

For a positive response YY in fixed units, the model log⁡Y=β0+β1x+ε\log Y = \beta_0 + \beta_1x + \varepsilon with independent errors ε∼N(0,σ2)\varepsilon \sim N(0, \sigma^2) describes multiplicative effects. Each unit of xx multiplies the conditional median of YY by eβ1e^{\beta_1}, the back-transformation eβ0+β1xe^{\beta_0 + \beta_1x} of the mean of log⁡Y\log Y is the conditional median of YY, and the conditional mean is larger by the factor eσ2/2e^{\sigma^2/2},

E(Y∣x)=eβ0+β1x+σ2/2.E(Y \mid x) = e^{\beta_0 + \beta_1x + \sigma^2/2} .

Nested models are compared with the partial F test. If a reduced model with pRp_R coefficients is a special case of a full model with pFp_F coefficients, both fitted to the same nn observations, then

F=(SSER−SSEF)/qSSEF/(n−pF),q=pF−pR,\begin{gathered} F = \frac{(\text{SSE}_R - \text{SSE}_F)/q}{\text{SSE}_F/(n - p_F)}, \\[0.4em] q = p_F - p_R, \end{gathered}

is compared with Fq, n−pFF_{q,\,n - p_F} under the normal error model. Adding predictors to a least-squares fit on the same data never increases SSE and never lowers R2R^2, while the adjusted value

Rˉ2=1−SSE/(n−p)SST/(n−1)\bar{R}^2 = 1 - \frac{\text{SSE}/(n - p)}{\text{SST}/(n - 1)}

can fall. With n=12n = 12 and SST=100\text{SST} = 100, models with 2 and 3 coefficients and SSE 40 and 30 have R2=0.60R^2 = 0.60 and 0.700.70, adjusted values 0.560.56 and about 0.6330.633, and partial F=3F = 3 on 1 and 9 degrees of freedom with p≈0.117p \approx 0.117.

The variance inflation factor VIF⁡j=1/(1−Rj2)\operatorname{VIF}_j = 1/(1 - R_j^2), where Rj2R_j^2 comes from regressing xjx_j on the other predictors, is the factor by which the correlation of xjx_j with the other predictors multiplies the variance of bjb_j. Multicollinearity makes individual coefficients unstable without necessarily harming predictions, and an exact linear relation among the predictors leaves the coefficients not identifiable. Choosing a model with the same data that are then used to test it makes the reported p-values and intervals too optimistic.

Lessons Transformations and Curved Relationships, Comparing Regression Models and Multicollinearity

Logistic regression

For a binary response with p(x)=P(Y=1∣x)p(x) = P(Y = 1 \mid x), logistic regression models the log odds as a linear function,

log⁡p(x)1−p(x)=β0+β1x,p(x)=11+e−(β0+β1x).\begin{aligned} \log\frac{p(x)}{1 - p(x)} &= \beta_0 + \beta_1x, \\[0.4em] p(x) &= \frac{1}{1 + e^{-(\beta_0 + \beta_1x)}} . \end{aligned}

The coefficient β1\beta_1 is the change in log odds for a one-unit increase in xx, so eβ1e^{\beta_1} is the odds ratio for that increase. The change in probability per unit of xx is not constant, and it is largest where p(x)p(x) is near 0.50.5. The coefficients are estimated by maximum likelihood, and when a predictor separates the outcomes 0 and 1 completely, no finite maximum likelihood estimate exists. A model is well calibrated when, among cases with predicted probability near some value, the observed share of ones is near that value. With β0=−2\beta_0 = -2 and β1=0.5\beta_1 = 0.5, p(0)≈0.119p(0) \approx 0.119 and p(4)=0.5p(4) = 0.5, the odds ratio per unit is e0.5≈1.65e^{0.5} \approx 1.65, and the probability rises by about 0.0630.063 from x=0x = 0 to x=1x = 1 but by about 0.1220.122 from x=4x = 4 to x=5x = 5.

Lessons Logistic Regression

Validation, overfitting and honest prediction

For mm evaluated predictions with errors ei=yi−y^ie_i = y_i - \hat{y}_i,

MSE⁡=1m∑i=1mei2,RMSE⁡=MSE⁡,MAE⁡=1m∑i=1m∣ei∣,\begin{gathered} \operatorname{MSE} = \frac{1}{m}\sum_{i=1}^{m} e_i^2, \\[0.4em] \operatorname{RMSE} = \sqrt{\operatorname{MSE}}, \\[0.4em] \operatorname{MAE} = \frac{1}{m}\sum_{i=1}^{m}\lvert e_i \rvert, \end{gathered}

and for a binary outcome with predicted probabilities pip_i the Brier score is the mean of (pi−yi)2(p_i - y_i)^2. Error on the training data is too optimistic, because the model was fitted to those cases, and a flexible model can fit them perfectly while predicting new cases badly, which is overfitting. Estimate prediction error on test data set aside before any modeling decision, or with kk-fold cross-validation, which repeats the whole procedure, preprocessing and variable selection included, on k−1k - 1 folds and scores the held-out fold. Data leakage, such as predictors recorded after the outcome, linked records on both sides of a split, or scaling with statistics of all the data, makes a score look better than real use would be. A test score describes data like the test data, and distribution shift in later use can make performance worse.

Lessons Validation, Overfitting and Honest Prediction

Bayesian Statistics

Bayesian statistics describes uncertainty about unknown quantities with probability distributions. The prior states what is assumed before the data, the likelihood links the parameter to the data, and the posterior combines the two. Every posterior statement is conditional on the model and the prior as well as on the data.

Prior, likelihood and posterior

For hypotheses H1,…,HkH_1, \dots, H_k with prior probabilities P(Hi)P(H_i) that add to 1, and data DD with P(D)>0P(D) > 0,

P(Hi∣D)=P(D∣Hi) P(Hi)P(D),P(D)=∑jP(D∣Hj) P(Hj),\begin{gathered} P(H_i \mid D) = \frac{P(D \mid H_i)\,P(H_i)}{P(D)}, \\[0.4em] P(D) = \sum_j P(D \mid H_j)\,P(H_j), \end{gathered}

so the posterior is proportional to the likelihood times the prior. For two hypotheses H1H_1 and H0H_0, with P(H0)>0P(H_0) > 0 and P(D∣H0)>0P(D \mid H_0) > 0,

P(H1∣D)P(H0∣D)=P(H1)P(H0) B10,B10=P(D∣H1)P(D∣H0),\begin{gathered} \frac{P(H_1 \mid D)}{P(H_0 \mid D)} = \frac{P(H_1)}{P(H_0)}\,B_{10}, \\[0.4em] B_{10} = \frac{P(D \mid H_1)}{P(D \mid H_0)}, \end{gathered}

so the posterior odds equal the prior odds times the Bayes factor B10B_{10}. When the observations are conditionally independent given each hypothesis, updating with one observation at a time gives the same posterior as updating with all of them at once. With prior probabilities 0.50.5 for each of two hypotheses that give a success the probabilities 0.20.2 and 0.60.6, one success raises the probability of the second hypothesis to 0.30/0.40=0.750.30/0.40 = 0.75, a Bayes factor of 3 in its favor.

Lessons Prior, Likelihood and Posterior

Bayesian estimation and credible intervals

The Beta⁡(α,β)\operatorname{Beta}(\alpha, \beta) distribution, with α,β>0\alpha, \beta > 0, has density proportional to pα−1(1−p)β−1p^{\alpha - 1}(1 - p)^{\beta - 1} on 0<p<10 < p < 1 and mean α/(α+β)\alpha/(\alpha + \beta). With a Beta⁡(α,β)\operatorname{Beta}(\alpha, \beta) prior for a success probability pp and yy successes in nn independent trials with that probability, the posterior is

p∣y∼Beta⁡(a,b),a=α+y,b=β+n−y,\begin{gathered} p \mid y \sim \operatorname{Beta}(a, b), \\[0.4em] a = \alpha + y, \quad b = \beta + n - y, \end{gathered}

and the posterior mean

α+yα+β+n\frac{\alpha + y}{\alpha + \beta + n}

is a weighted average of the prior mean α/(α+β)\alpha/(\alpha + \beta) and the sample proportion y/ny/n, with weights proportional to α+β\alpha + \beta and nn. A 95 percent credible interval contains pp with posterior probability 0.950.95 given the prior, the model and the data, and the equal-tailed version runs from the 0.0250.025 to the 0.9750.975 posterior quantile. A 95 percent confidence interval instead makes a statement about the procedure over repeated samples, and the two intervals can differ in value as well as in meaning.

A Beta⁡(2,2)\operatorname{Beta}(2, 2) prior and 7 successes in 10 trials give the posterior Beta⁡(9,5)\operatorname{Beta}(9, 5), with mean 9/14≈0.6439/14 \approx 0.643, median about 0.6500.650, 95 percent equal-tailed credible interval about [0.386,0.861][0.386, 0.861] and posterior probability P(p>0.5∣y)≈0.867P(p > 0.5 \mid y) \approx 0.867.

Lessons Bayesian Estimation and Credible Intervals

Posterior prediction and prior sensitivity

The posterior predictive distribution of new data averages the model over the posterior, so it includes the uncertainty about the parameter as well as the randomness of the new observations. With the posterior Beta⁡(a,b)\operatorname{Beta}(a, b), the next trial succeeds with probability E(p∣y)=a/(a+b)E(p \mid y) = a/(a + b), and the number KK of successes in mm new trials that are independent given pp has

P(K=k∣y)=(mk)B(a+k, b+m−k)B(a,b)\begin{aligned} &P(K = k \mid y) \\[0.4em] &\quad = \binom{m}{k}\frac{B(a + k,\ b + m - k)}{B(a, b)} \end{aligned}

for k=0,…,mk = 0, \dots, m, where BB is the beta function. Plugging a single estimate of pp into the binomial formula ignores the uncertainty about pp and gives a predictive distribution that is too narrow. With the Beta⁡(9,5)\operatorname{Beta}(9, 5) posterior and m=2m = 2, the probabilities of 0, 1 and 2 successes are 1/71/7, 3/73/7 and 3/73/7, while plugging in 9/149/14 gives 45/98≈0.45945/98 \approx 0.459 for one success instead of 3/7≈0.4293/7 \approx 0.429.

Refitting with other reasonable priors shows how much a conclusion depends on the prior. With the same 7 successes in 10 trials, a Beta⁡(1,1)\operatorname{Beta}(1, 1) prior gives posterior mean 2/32/3 and a Beta⁡(20,20)\operatorname{Beta}(20, 20) prior gives 0.540.54. A prior predictive check simulates data from the prior and the model before the data are used, and a posterior predictive check compares the observed data with data replicated from the posterior, looking for features the model fails to reproduce.

Lessons Posterior Prediction and Prior Sensitivity

Dependent Data and Time Series

Many standard formulas assume independent observations. Readings from the same person or cluster and values recorded over time are often positively correlated, and then the usual standard errors are too small and random splits for validation are too optimistic.

Repeated measures, clusters and independence

Pseudoreplication treats repeated measurements of one unit, or units inside one assigned cluster, as independent replicates. In the random-intercept model Yij=μ+bi+eijY_{ij} = \mu + b_i + e_{ij}, with independent cluster effects bib_i of variance τ2\tau^2 and independent errors eije_{ij} of variance σ2\sigma^2, two observations in the same cluster have the intraclass correlation

ρ=τ2τ2+σ2,\rho = \frac{\tau^2}{\tau^2 + \sigma^2},

and with clusters of mm observations the variance of the overall mean is D=1+(m−1)ρD = 1 + (m - 1)\rho times its value under independence. Analyze at the level of the units that were sampled or assigned independently, for example with one summary per cluster, a cluster bootstrap that resamples whole clusters, or a mixed model with a random intercept for each cluster. With clusters of unequal size, the mean of the cluster means and the mean of all the observations estimate different quantities.

Four devices measured three times each, with readings (7,8,9)(7, 8, 9), (9,10,11)(9, 10, 11), (11,12,13)(11, 12, 13) and (13,14,15)(13, 14, 15), have device means 8, 10, 12 and 14. The standard error of the overall mean computed from the four device means is (20/3)/4≈1.29\sqrt{(20/3)/4} \approx 1.29, while treating the 12 readings as independent gives about 0.720.72.

Lessons Repeated Measures, Clusters and Independence

Time series, trend, seasonality and autocorrelation

A time series records one variable at successive times, and its order carries information. A trend is a long-run change in level, seasonality is a pattern that repeats with a fixed period, and the autocorrelation at lag kk is the correlation between values kk steps apart. With deviations dt=yt−yˉd_t = y_t - \bar{y}, the sample autocorrelation is

rk=∑t=1n−kdt dt+k∑t=1ndt2.r_k = \frac{\sum_{t=1}^{n-k} d_t\,d_{t+k}}{\sum_{t=1}^{n} d_t^2} .

The values 1, 2, 3, 4 and 5 in that order have r1=0.4r_1 = 0.4, and the same values in the order 1, 5, 2, 4, 3 have r1=−0.7r_1 = -0.7. A series is stationary in the weak sense when its mean and variance stay constant and the covariance between two values depends only on the lag between them. Trend and seasonality break stationarity, and differencing, yt−yt−1y_t - y_{t-1}, or seasonal differencing, yt−yt−sy_t - y_{t-s} for period ss, often removes them.

Positive autocorrelation makes the variance of a mean larger than σ2/n\sigma^2/n. For 10 values from a stationary series with variance 4 and autocorrelations ρk=0.5k\rho_k = 0.5^k, the SE of the mean is about 1.021.02, against 0.630.63 for independent values. A change seen in a time plot does not by itself identify its cause.

Lessons Time Series, Trend, Seasonality and Autocorrelation

Smoothing, forecasting and time-aware validation

A forecast y^t+h∣t\hat{y}_{t+h \mid t} is made at origin tt for horizon hh and uses only the values up to time tt.

MethodForecast from origin tt
Naiveyty_t for every horizon
Seasonal naive with period ssthe last observed value from the same season
Trailing moving average of ww values1w(yt+yt−1+⋯+yt−w+1)\dfrac{1}{w}(y_t + y_{t-1} + \cdots + y_{t-w+1})
Simple exponential smoothingthe level ℓt=αyt+(1−α)ℓt−1\ell_t = \alpha y_t + (1 - \alpha)\ell_{t-1}, with smoothing constant 0<α≤10 < \alpha \le 1

A centered moving average uses later values, so it can describe the past but cannot forecast. Simple exponential smoothing with α=0.5\alpha = 0.5 and ℓ1=y1\ell_1 = y_1, applied to 10, 12, 11, 13, 12, 14, 13 and 15, gives the levels 10, 11, 11, 12, 12, 13, 13 and 14, so every forecast from time 8 is 14.

Rolling-origin evaluation fits the method at each origin using only the data available then, forecasts ahead, and scores the error yt+h−y^t+h∣ty_{t+h} - \hat{y}_{t+h \mid t} when the value arrives. Random splits, and preprocessing or tuning that uses later data, let information from the future leak into the evaluation, which is temporal leakage. A useful method should beat the naive and seasonal naive baselines on such an evaluation. A forecast interval needs a probability model for the future errors, and it usually widens as the horizon grows.

Lessons Smoothing, Forecasting and Time-Aware Validation

Complete Statistical Investigations

A statistical result means little without its question, design and limits. A complete investigation runs from a precise question and its estimand through design, measurement, exploration and a method suited to the design, to model checks and a conclusion that says no more than the evidence supports.

Choosing a method

Choose the method from the question, the type of outcome and the design, before seeing the results, and check its conditions on the data.

Question and dataUsual methods
One meanone-sample t interval and test, or the sign test for a median
One proportionWilson or Clopper-Pearson interval, exact binomial test
Paired measurementspaired t on the differences, or a sign or signed-rank test
Two independent meansWelch t interval and test, or the rank-sum test to compare distributions
Two independent proportionsunpooled interval for the difference, two-proportion z test, Fisher’s exact test for small counts
Paired yes or no outcomesMcNemar test
Several meansone-way or Welch ANOVA, then planned contrasts or Tukey comparisons
Several distributionsKruskal-Wallis test
Counts in categorieschi-square goodness-of-fit, independence or homogeneity test
Numerical response and predictorslinear regression with residual checks
Binary response and predictorslogistic regression
Clustered or repeated measurementsanalysis at the cluster level, cluster bootstrap or mixed model
Values over timetime-aware methods and rolling-origin evaluation

Lessons Selecting Methods and Reporting Statistical Results

Planning and reporting

  • Estimand. State the quantity the study aims to learn, with its population, variable, comparison and summary, such as μB−μA\mu_B - \mu_A in minutes.
  • Analysis plan. Fix the primary outcome, the method, the handling of missing data and the comparisons before the outcome data are seen, and preregister the plan when possible. Label analyses chosen after looking at the data as exploratory.
  • Selective reporting. Report every comparison that was made, not only the significant ones, since selection inflates false positives.
  • Effects and uncertainty. Give the estimate in its units with a confidence interval, then the p-value with the test named, and compare the interval with the smallest effect that would matter.
  • Scope. Generalize to a population only as far as the sampling supports, and claim causation only as far as the assignment supports.
  • Sensitivity analysis. Repeat the analysis under other reasonable assumptions, such as other values for missing data or without influential points, and report how much the conclusion moves.
  • Reproducibility. Keep the raw data, the code, the software versions, the seeds and the cleaning log, so that every number can be recomputed.

For example, two independent groups of 12 with mean completion times of about 16.1716.17 minutes for A and 12.7512.75 minutes for B give the Welch estimate yˉB−yˉA≈−3.42\bar{y}_B - \bar{y}_A \approx -3.42 minutes, with 95 percent interval about [−5.07,−1.76][-5.07, -1.76] minutes and two-sided p-value about 0.00030.0003. A report states the difference and its interval in minutes first, says that the p-value is computed assuming no true difference and the conditions of the Welch test, and compares the whole interval with the smallest difference that would matter.

Lessons Selecting Methods and Reporting Statistical Results, A Complete Statistical Investigation