Home

MA012 Statistics II

Your study guide

Statistics from the very beginning, then all six lectures, in simple English, with pictures, worked examples and the lecturer's own words.

Start from zero

How to read this guide

The same kinds of block appear everywhere, so you quickly learn what to read and what to skip.

  • Key ruleThe formula or rule to remember.
  • In plain wordsThe idea without mathematics. Read this first when something looks hard.
  • LecturerReal sentences from the recordings. L3 12:40 means recording 3, at 12 minutes 40 seconds. L1a is the extra recording for Lecture 1.
  • ExampleA real calculation from the lectures, step by step.
  • Watch outA common mistake to avoid.
  • Check yourselfA question to answer before you open the answer.
  • Revise fast: in a lecture, use Key points, Examples or Questions at the top to see only those blocks.
  • Try it: boxes with sliders let you change a number and watch the result change. Charts show values when you point at them.
  • Track progress: press Mark as studied at the end of a topic. Your browser remembers it, and this page offers to continue where you stopped.
  • Find anything: press / to search all topics. Click a figure to enlarge it, and use Copy code on any R block.

Course rules the lecturer told you

From the first minutes of Lecture 1. The official version is in the interactive syllabus in IS, so check there if something is unclear or has changed.

PartPointsWhat it is
Report 1 and report 210 + 10At the beginning of two seminars. Details at least two weeks before.
Final practical assignment20At the last seminar, 100 minutes. Tidyverse only: no basic R syntax or basic R graphics.
Needed to reach the exam20 of 40Below 20 points, you get result X and cannot take the exam.
Final exam60In the examination period.
  • Seminars are mandatory and you must actively work there. You can miss two without an excuse. Other absences go through the study office.
  • Lectures are not mandatory, and the recordings are in IS.
  • Everything is given in English, but you may answer in Czech, Slovak or English.
  • You must understand the theory too, not only use the functions. This is the main difference from MV013.

In the Statistics for Computer Science course you are expected only to be able to practically use the methods. In this course you are asked to understand also the theory, to be able to correctly use it, to be able to distinguish the methods, to use the correct method for the situation about the data.

Lecturer L1 13:22

Where the content comes from

  • Lectures 1 to 5 use your lecture materials and transcripts. The transcripts were made by a machine, so in the quotes I fixed obvious mistakes and shortened some sentences. The meaning is unchanged.
  • Lecture 6 had no transcript, so it has no lecturer quotes.
  • Statistics from zero is not in your lecture material. I wrote it as the background that the lectures assume. It uses your course's data and quotes where they fit.
  • My additions: the "In plain words" blocks, extra intuition, most practice questions, and answers where a lecture gave none are mine. Treat them as help.
  • Corrections: where the lecture material seems to contain a small error, this guide uses the corrected form. See the list.

Start here · The background the lectures assume

Statistics from zero

The course is called Statistics II. The lectures expect you to have taken Statistics I, so they often say "you know this" and move on. This part teaches that missing course from the very beginning. You need only basic school mathematics.

This requires you to remember what are confidence intervals, and maybe you were forced to learn, or maybe you can even remember, some formulas for confidence intervals.

Lecturer L1a 24:05
In plain words

Read this part in order. Each topic uses the one before it. It is not taken from your lecture material: I wrote it as background. The data and the quotes are from your course. Every number was checked in R.

0.1What statistics is for

Suppose you want to know how much weight people lose on a diet. You cannot test every person on Earth, so you test a few and try to say something about all of them. That jump, from a few to all, is what statistics is about.

Populationeverybody you care abouttrue mean μ, true SD σunknown Samplethe few you measuredn people, pickedat random Statisticcalculated from the samplesample mean x̄, SD sknown draw calculate Inference: use the statistic to say something about μ, and say how precise it is
The whole of statistical inference in one picture. You can calculate the statistic. You want to know the parameter.
WordMeaningDiet example
Population populaceEverybody or everything you care aboutall people who could follow this diet
Sample výběrThe part you really measuredthe 24 people on diet A
Parameter parametrA true number about the population. Fixed, but unknown. the true mean weight loss
Statistic statistikaA number calculated from the sample. Known, but it changes from sample to sample. kg, the sample mean
Estimate odhadA statistic used as a guess of a parameter" is probably near 3.3 kg"

The next table is worth learning now, because the lectures use these letters on almost every page. Greek letters are the true values. Latin letters are what you calculate.

What it measuresTrue value (population)From the sample
mean "mu" "x bar"
standard deviation "sigma"
variance
proportion or "p hat"
correlation "rho"
regression coefficient "beta" "beta hat"

A hat always means "an estimate of". So is an estimate of

Statistics is never about perfect data. If you have perfect data, you need the probability, not the statistics. Statistics is about imperfect data: how to gain information, not perfect but approximate information, from approximate data.

Lecturer L1 38:23
Check yourselfA poll of 1,000 voters finds that 52 % support a party. Which number is the statistic, and what is the parameter?

The statistic is 52 %, because it was calculated from the sample. The parameter is the true share among all voters, which nobody knows.

0.2How to read the symbols

Formulas look hard mostly because of the notation. Each symbol is a short way of saying something simple.

SymbolRead it asExample
the -th value is the third value
how many values you have
add all values, from the first to the -th
and capital: random, before you measure. Small: the number you got. is "the next roll", is what it showed
"has the distribution"
the probability of event
the probability of if is true
expected value, variancetopic Random variables
null hypothesis, alternative hypothesistopic The idea of a test
"is inside", "is not inside"
both and rolled a six and it was even
"plus or minus": gives two numbers gives 3 and 7
the two error risks of a test (also used for other things)
or quantile: the value with share on its left
"approximately has this distribution, when is large"
Example

Reading a sum

Take the values Then:

The second formula is the sample mean. "Add everything, then divide by how many" looks long in symbols, but it is the usual average.

0.3The centre of the data: mean and median

The first question about any data is: what is a typical value? We use a real sample from Lecture 3: ten people had to guess when one minute had passed, in seconds.

MeasureWhat it isOn these data
Mean Add all values, divide by
Median Sort the values and take the middle one. With an even take the average of the two middle ones.Sorted: 45, 48, 50, 51, 53, 55, 56, 58, 63, 66. So
ModeThe most frequent valuenone here, because each value appears once

Why have two measures of the centre? Suppose somebody mistypes 66 as 166.

meanmedian
406080100120140160the ten guesses in secondsmean 54.5median 54406080100120140160the same guesses, with 66 mistyped as 166mean 64.5median 54
One wrong value pulls the mean from 54.5 up to 64.5. The median stays at 54.
In plain words

The mean uses the size of every value, so one extreme value can move it a lot. The median uses only the order, so it does not care how extreme a value is. We say the median is robust to outliers odlehlé hodnoty. This simple fact is the whole reason for the rank-based tests of Lecture 3.

Check yourselfFive salaries: 30, 32, 35, 38, 300 thousand. What are the mean and median? Which describes a typical person better?

The mean is and the median is 35. The median is better here, because 87 is more than everybody earns except one person.

0.4The spread of the data: variance and standard deviation

A centre is not enough. Two classes can have the same mean mark, but in one class everybody is close to the mean and in the other class the marks are all over the place. We need a number for how far values usually are from the mean.

4050607012345678910personguess in secondsmean 54.5mean + s = 61.05mean − s = 47.95
Each vertical line is one deviation: how far one guess is from the mean. The standard deviation is a kind of typical length of these lines.

Build it step by step on a tiny sample, with mean 5:

deviation squared
2−39
4−11
4−11
500
10+525
sum036
  1. Find each deviation from the mean.
  2. Square them. The plain deviations always add up to 0, so their average tells you nothing. Squares are never negative.
  3. Add the squares. This is the sum of squares, here 36. ANOVA is built on this quantity.
  4. Divide by This gives the variance:
  5. Take the square root. This gives the standard deviation:
Sample variance and standard deviation

Why the square root? Squaring also squares the unit. If the data are in kilograms, the variance is in kilograms squared, which means nothing to a person. The standard deviation is back in kilograms. So we calculate with the variance, and we talk about the standard deviation.

Why and not See Good and bad guesses below.

Example

The one-minute data

The mean is 54.5, and the sum of squares is So and seconds. A guess is usually about 6.5 seconds from the mean.

R
x <- c(53, 48, 45, 55, 63, 51, 66, 56, 50, 58)
mean(x)
[1] 54.5
var(x)
[1] 42.94444
sd(x)
[1] 6.553201

If you say 3 kilograms, it's almost useless information in statistics. If you add the information, it is 3 kilograms with standard deviation of 100 grams, this is a proper statistical result.

Lecturer L1 41:05
Check yourselfAll five values in a sample are equal to 7. What is the standard deviation?

It is 0. All deviations are 0, so there is no spread at all.

Check yourselfYou convert a sample from metres to centimetres, so each value is multiplied by 100. What happens to the mean, the SD and the variance?

The mean and the SD are multiplied by 100. The variance is multiplied by because it is made of squares.

0.5Quartiles, box plots and histograms

Quartiles cut the sorted data into four equal parts. Q1 has about 25 % of the values below it, the median (Q2) has 50 %, and Q3 has 75 %. The interquartile range, IQR = Q3 − Q1, is the width of the middle half of the data.

4550556065guess in secondslowest 45Q1 = 50.25median = 54Q3 = 57.5highest 66
A box plot of the one-minute data, with the ten real values as dots under it. The box holds the middle 50 % of the data, and the thick line is the median.
  • The whiskers reach to the most extreme values that are still at most 1.5 × IQR from the box.
  • Points beyond the whiskers are drawn one by one, and they are possible outliers.
  • A box plot shows the median, not the mean.
R
quantile(x)
   0%   25%   50%   75%  100%
45.00 50.25 54.00 57.50 66.00
IQR(x)
[1] 7.25

A histogram shows the shape of the data: cut the axis into bins, and draw a bar for how many values fall in each one. The shape tells you how the mean and median relate:

meanmedian
Symmetric: mean = median
01234
Long right tail: mean above median
01234
Long left tail: mean below median
01234
The mean is pulled towards the long tail. Income and waiting times usually have a long right tail. Many tests in this course first ask: is the shape close to the symmetric bell?
Check yourselfA histogram has a long tail to the right. Which is larger, the mean or the median?

The mean. The few very large values pull it to the right, and the median does not react to how large they are.

0.6Probability from zero

A probability pravděpodobnost is a number from 0 to 1. It says how often something would happen if you repeated the situation many times. means "about half of the time". Everything in statistics is built on four rules.

RuleFormulaExample with a die
Opposite (complement)
Or, for events that cannot happen together
And, for independent eventstwo sixes in two rolls:
If (conditional)

Independent means that knowing one result tells you nothing about the other. Two rolls of a die are independent. Your height and your weight are not.

Example

The "at least one" trick

What is the chance of at least one six in four rolls? Counting all the ways is painful. The opposite is easy: no six at all.

This exact trick gives the familywise error rate in Lecture 1: replace "a six" with "a false alarm" and with

Watch out

is not The chance that a person is tall if they play professional basketball is high. The chance that a person plays professional basketball if they are tall is tiny. The p-value depends on this difference.

Check yourselfA test has a 5 % chance of a false alarm. You run 3 independent tests. What is the chance of at least one false alarm?

about 14 %. The lecturer used this exact number to introduce ANOVA.

0.7Random variables, expected value and variance

A random variable is a number whose value depends on chance, like the result of a roll. Its distribution lists the possible values and how likely each one is.

One die: every value equally likely
00.050.10.150.2123456value on the dieprobabilityE(X) = 3.5
Heads in 10 fair coin flips
00.10.20246810number of headsprobabilityE(X) = 5
Two discrete distributions. Each bar is the probability of one value, and all the bars add up to 1.

The expected value střední hodnota is the long-run average: each value times its probability, all added up. For a die:

You can never roll 3.5. It is the average of many rolls. The variance is the expected squared distance from the mean:

These are the same ideas as and but for the whole theoretical distribution. So is and is

Rules you will need, for constants a and b
  • Adding a constant moves the data, but does not change the spread.
  • always.
  • only if and are independent.

The binomial distribution counts successes in independent tries, each with success probability We write Then and For 10 fair coin flips, and The sign test in Lecture 3 and the chi-squared test in Lecture 4 both rely on this.

Check yourself has mean 10 and variance 4. What are the mean and variance of

The changes the mean, but not the variance.

0.8Continuous variables: probability is an area

Height can be any number, like 170.2371 cm. The chance of exactly that value is 0, so bars for single values make no sense. Instead we ask about ranges, like "between 160 and 180 cm".

Imagine a histogram of many people's heights. With more data and narrower bins, the top of the bars turns into a smooth curve, called the probability density function (PDF) hustota pravděpodobnosti.

00.010.020.030.04140150160170180190200height in cmdensityarea from 160 to 180 = 0.68
Bars of a histogram with the density curve over them. The darker bars are the people from 160 to 180 cm: 68 % of the total area.
How to read a density curve
  • Probability is the area under the curve, not the height of the curve.
  • The whole area under the curve equals 1.
  • A taller curve at some place means that values near there are more common.

If you said that both areas are equal to one, I hope everybody can see that the red area is much bigger than the yellow area. But you must look at the scale. It is mandatory: each mathematical plot must have the scales on the axis.

Lecturer L1 86:06
Check yourselfCan a density curve be higher than 1?

Yes. The height is not a probability, only the area is. A very narrow curve must be tall so that its area is still 1. You will see this in the next topics, because the curve of a sample mean gets narrower and taller as grows.

0.9The normal distribution and z-scores

The normal distribution normální rozdělení, also called Gaussian, is the famous bell curve. Two numbers describe it fully: the mean says where the centre is, and the standard deviation says how wide it is. We write

Watch out

The second number in is the variance. In R, functions take the standard deviation: pnorm(x, 3, 2).

00.10.20.30.4μ−3σμ−2σμ−σμμ+σμ+2σμ+3σdensity68.3 %95.4 %99.7 %
The 68-95-99.7 rule holds for every normal distribution. Point at the curve to read values.

To compare normal variables, we convert them to a common scale. The z-score standardizovaná hodnota says how many standard deviations a value is from the mean:

Standardization

is the standard normal distribution. So a question about any normal variable becomes a question about a single curve.

Example

Heights: from a value to a probability

Heights follow What share of people are taller than 185 cm?

  1. Convert to a z-score:
  2. Find the area to the left of it is 0.933.
  3. We want the right side: about 6.7 %.
00.010.020.030.04140150160170180190200height in cmdensity185 cm: z = 1.5area = 0.067
R
1 - pnorm(185, mean = 170, sd = 10)
[1] 0.0668072
Example

Heights: from a probability to a value

How tall must you be to be in the tallest 10 %? This is the reverse question. We need the value with 90 % of the area on its left, the 90 % quantile.

The z-score with 0.90 on its left is 1.2816. So cm.

R
qnorm(0.90, mean = 170, sd = 10)
[1] 182.8155

R uses the same four letters for every distribution. Learn these, and you know the functions for all of them. Replace norm with t, chisq, f, binom or exp.

FunctionQuestion it answersExample
pnormprobability: what is the area to the left of this value?pnorm(1.96) gives 0.975
qnormquantile: which value has this area to its left?qnorm(0.975) gives 1.96
dnormdensity: how high is the curve here?dnorm(0) gives 0.399
rnormrandom: draw random valuesrnorm(5) gives 5 random values

Where the number 1.96 comes from

You will see 1.96 all the time. It cuts off the middle 95 % of the standard normal curve, which leaves 2.5 % in each tail.

00.10.20.30.4-3-1.96-1011.963zdensitymiddle 95 %2.5 %2.5 %
Middle areaEach tailQuantileValue
90 %5 %1.645
95 %2.5 %1.960
99 %0.5 %2.576

Read this subscript carefully. For a middle area of the upper limit has on its left. With that is This is why you see in nearly every formula of the course.

Check yourselfExam points follow You got 76. What is your z-score, and roughly what share of people did better?

About 95 % of people are within 2 SD of the mean, so about 2.5 % are above you (more exactly 2.3 %).

0.10The key idea: the sample mean is random too

This is the most important idea of the whole course, and it is the one most people miss. Test 10 people and you get a mean of 54.5 seconds. Test 10 other people and you get a different mean. So the sample mean is itself a random variable, and it has its own distribution. That distribution is called the sampling distribution výběrové rozdělení.

How wide is it? Use the rules from Random variables. Each has mean and variance and they are independent.

Standard error of the mean

The standard error (SE) střední chyba průměru is the standard deviation of the sample mean:

one personmean of 4mean of 16mean of 64
00.10.20.30.40.5354045505560657075value in secondsdensity
One person varies a lot. The mean of 4 people varies half as much, the mean of 16 a quarter as much, and the mean of 64 an eighth as much.
Standard deviation, Standard error,
Describeshow much people differ from each otherhow much your guess of the mean would change in a new sample
With more datastays about the samegets smaller
One-minute data6.55 seconds seconds
Watch out

To cut the standard error in half, you need four times as much data, because of the square root.

Check yourselfA sample of 25 has What is the SE? What sample size would give an SE of 1?

For an SE of 1, you need so

0.11The central limit theorem

The last topic told us the centre and the width of the sampling distribution. What about its shape? This is the surprising part.

Central limit theorem (informally)

Take independent values from almost any distribution with a finite variance. When is large, the sample mean is approximately normal:

Try it. Start with "Long tail" and which is nothing like a bell. Now raise to 5, 30 and 100.

Once you have independent observations and you take average of the independent observations, after standardization, it means take the value minus the mean and divide it by the standard deviation, you will obtain something close to standard normal distribution. The central limit theorem is saying that regardless of the probability distribution of the original variable, after taking the average of many, many values, you are going more and more close to the normal distribution.

Lecturer L3 48:47
In plain words

Why does this happen? Extreme values are rare, and they tend to be balanced by ordinary values when you average. Very high averages need many very high values at the same time, which almost never happens.

This theorem is everywhere in the course:

  • ANOVA and t-tests are robust to non-normal data, because they really work with means (Lecture 2).
  • The binomial looks normal for large , because a count is a sum of zeros and ones. This special case is the de Moivre-Laplace theorem used in the sign test and the chi-squared test.
  • Asymptotic versions of the rank tests in Lecture 3 use it too.
Watch out

The theorem is about the mean, not about the data. More data does not make your data more normal: a histogram of 10,000 skewed values is still skewed.

Check yourselfWaiting times have a long right tail, and you have Is the sample mean approximately normal? Are the data?

The mean is approximately normal, by the central limit theorem. The data are not: they keep their long right tail.

0.12Good and bad guesses: estimators

An estimator odhad is a rule for guessing a parameter, like "take the sample mean". There are two kinds of estimate:

  • A point estimate is one number: "the mean is 54.5".
  • An interval estimate is a range: "the mean is between 49.8 and 59.2". This is a confidence interval.

What makes an estimator good?

PropertyMeaningPicture
UnbiasedOn average over many samples, it hits the true value: Arrows centred on the target
Low varianceIt changes little from sample to sample.Arrows close together
ConsistentIt gets closer to the true value as grows.More data, better aim

Unbiased estimator is an estimator whose expected value is exactly equal to the theoretical value. Imagine a case that you have 1000 samples from the same population. If you really use 1 over n minus 1 and you evaluate the sample variance on each sample, and take an average of these 1000 values, this will be a good estimator of the variance from the theory.

Lecturer L5 9:01
Example

Why we divide by n − 1: every possible sample

Take a very small population: the values Its true mean is and its true variance is

List all 9 possible samples of size 2 (each draw can be any of the three values). For each one, calculate the variance in both ways.

Samplemeandivide by divide by
1, 11.00.00.00
1, 21.50.50.25
1, 32.02.01.00
2, 11.50.50.25
2, 22.00.00.00
2, 32.50.50.25
3, 12.02.01.00
3, 22.50.50.25
3, 33.00.00.00
average of 92.00.6670.333

The average of the sample means is 2, exactly Dividing by gives on average, exactly Dividing by gives which is too small.

In plain words

Why too small? The deviations are measured from the sample's own mean, and that mean always sits in the middle of the sample. So the values look closer together than they really are. Dividing by a smaller number corrects this. The lost "one" is the degree of freedom used up by estimating the mean.

0.13Confidence intervals: the idea

You measured 10 people and got a mean of 54.5 seconds. Is the true mean exactly 54.5? Almost certainly not, because another sample would give another number. A single number hides this uncertainty. A confidence interval (CI) interval spolehlivosti shows it, by giving a range of believable values for the parameter.

Every common confidence interval has this form
  • Estimate: your best single guess, like
  • Standard error: how much that guess usually changes between samples.
  • Critical value: how many standard errors you need for the confidence you want, like 1.96 for 95 %.
In plain words

Think of fishing with a net. A point estimate is a spear: you throw at one exact spot, and you will almost surely miss. An interval is a net: it covers a range, so it can catch the fish. A bigger net catches more often, but tells you less exactly where the fish is. The fish does not move. Your net lands in a different place each time.

0.14Building a 95 % interval, step by step

Suppose for a moment that we know From the last topics, we know how the sample mean behaves:

  1. The sample mean is normal around the true mean, with standard deviation So after standardizing:
  2. 95 % of the standard normal lies between ±1.96:
  3. Multiply everything by
  4. Rearrange to get alone in the middle:
95 % CI for a mean, if σ is known

The picture shows why this works. The sample mean lands within 1.96 SE of in 95 % of samples. Exactly in those samples, an interval of ±1.96 SE around reaches

true μ2.5 %2.5 %x̄ lands here 95 % of the time−3 SE−2 SE−1 SEμ+1 SE+2 SE+3 SEsample 1sample 2sample 3: missessample 4
Top: where the sample mean can land. Bottom: four samples, each with its own interval of the same width. Sample 3 landed in the red tail, so its interval misses μ. All the others catch it.
Example

Pretend that σ = 7 is known

One-minute data:

0.15The real case: σ is unknown, so we use t

In practice nobody tells you You estimate it with But also changes from sample to sample, which adds extra uncertainty. William Gosset, working at the Guinness brewery and writing as "Student", worked out the exact result in 1908:

The Student t distribution looks like the normal curve, but with heavier tails. It depends on the degrees of freedom, here With more data, becomes reliable, and approaches the normal curve.

N(0, 1)t with 9 dft with 2 df
00.10.20.30.4-5-4-3-2-1012345valuedensity
Small samples have heavy tails, so the interval must be wider. With 9 df the curve is already close to normal.
df2491930751001000normal
4.3032.7762.2622.0932.0421.9921.9841.9621.960
The CI for a mean: the one you will really use

Assumption: a random sample from a normal distribution, or a large enough sample for the central limit theorem to work.

Example

The whole calculation by hand, on the one-minute data

  1. Estimate:
  2. Standard deviation:
  3. Standard error:
  4. Critical value: df, and 95 % confidence means
  5. Margin of error:
  6. Interval: which gives seconds.
46485052545658606264mean guess in secondsH₀: 6049.8159.19x̄ = 54.5, margin ±4.69
R
qt(0.975, df = 9)
[1] 2.262157
t.test(x)$conf.int
[1] 49.81212 59.18788
attr(,"conf.level")
[1] 0.95

In words: we are 95 % confident that the true mean guess lies between 49.8 and 59.2 seconds. The whole interval is below 60, so people seem to guess too early. This is already a test, as you will see below.

Check yourselfA sample has and Find the 95 % CI.

The margin is The CI is

0.16What "95 % confident" really means

This is the most common mistake in all of statistics, and a favourite exam question. The true mean is a fixed number. It is not random. Before you collect data, the interval is random: it depends on the sample that you will get.

The correct meaning

If you repeat the whole study many times and build a 95 % interval each time, about 95 % of those intervals will contain the true value. "95 %" describes how reliable the method is.

Press "Draw 30 new samples" a few times. Each time, the red lines are different, but about 5 % of the lines miss. In real life you get only one line, and you can never know whether yours is one of the red ones.

Sentence about the interval (49.81; 59.19)Why
"We are 95 % confident that the true mean is between 49.81 and 59.19."OKThe usual short way to say it. "Confident" refers to the method.
"This method catches the true mean in 95 % of samples."CorrectThe exact meaning.
"There is a 95 % probability that is in (49.81; 59.19)."Wrong is fixed and the numbers are now fixed too. It is either inside or not. We simply do not know which.
"95 % of people guessed between 49.81 and 59.19 seconds."WrongThe interval is about the mean, not about individuals. Only some of the ten guesses are inside it.
"95 % of future sample means will fall in this interval."WrongThe 95 % is about catching not about where the next mean lands.
Watch out

Your lecture material says that the CI "contains the true value of the parameter with given probability". Read this as a statement about the method before you have the data. After you have calculated your numbers, use the wording in the first two rows.

Check yourselfYour friend says: 'My 95 % CI is (10; 14), so there is a 5 % chance that the mean is outside it.' What is wrong?

The true mean and the numbers 10 and 14 are all fixed, so this particular interval either contains it or does not. The 5 % is the share of intervals, over many samples, that miss the true mean.

0.17What makes an interval narrow or wide

A narrow interval tells you more. Look at the margin of error, Three things control it.

ChangeEffect on the intervalWhy
Larger sample narrower is in the denominator, and gets smaller too
Less variable data narrower is in the numerator. Better measurements help.
Higher confidence levelwiderTo be more sure of catching the fish, you need a bigger net
One-minute dataintervalwidth
90 %1.833(50.70; 58.30)7.60
95 %2.262(49.81; 59.19)9.38
99 %3.250(47.77; 61.23)13.47

The 99 % interval contains 60, and the 95 % interval does not. This is why the level must be fixed before you look at the data.

02468020406080100120140160180200sample size nmargin of error (s)n = 10: ±4.34n = 40: ±2.17n = 160: ±1.08
Margin of error with σ = 7 and 95 % confidence. Four times the data gives half the margin, so precision gets expensive.
Example

How many people do I need?

You want a margin of at most seconds at 95 %, with Solve for

Always round up. For a margin of 1 second you need half the margin takes four times the people.

Check yourselfYou double the sample size. By what factor does the margin of error change (roughly)?

It is divided by so it becomes about 71 % of its old size. It does not halve.

0.18Comparing two groups: rebuilding R's interval

Very often the parameter of interest is a difference, like The form is the same: estimate ± critical value × standard error. Only the standard error changes. For independent samples, variances add (the rule above):

CI for a difference of two means (Welch)
Example

Where R's numbers for the diets come from

In Lecture 1, R reports the interval without explaining it. Now we can rebuild it.

  1. Estimate: kg.
  2. Standard error:
  3. Critical value:
  4. Margin of error:
  5. Interval: which gives ✓
-4-3-2-101difference in means μA − μC (kg)H₀: 0−3.15−0.54−1.85, margin ±1.30
0 is outside the interval, so diets A and C differ at the 5 % level. All believable differences are negative: diet A loses less.

How to read it: diet C loses between 0.54 and 3.15 kg more than diet A on average, with 95 % confidence. This says more than a p-value does, because it shows the size of the effect.

Paired data

If the same people are measured twice, before and after, the two samples are not independent. Calculate the difference for each person, and use the one-sample interval on those differences. The formula above would be wrong, because it adds variances as if the samples were independent.

One-sided intervals

A one-sided test has a one-sided interval, open on one side. All of goes to one tail, so the critical value uses not

Example

The diets again, with H₁: μA < μC

so the upper limit is The interval is which is exactly what R prints as -Inf -0.75944. It does not contain 0, so reject

A trap: overlapping intervals

Watch out

Two overlapping intervals do not prove that two groups are the same. To compare two groups, look at the interval for their difference.

Example

Real numbers from the diets

Using the ANOVA results, the 95 % CI for diet A is and for diet C it is They overlap. But the 95 % CI for the difference, built from the same is with So the means do differ.

01234567mean weight loss (kg). The intervals overlap a little.diet A: (2.33; 4.27)diet C: (4.23; 6.07)-2-10123456difference (kg). 0 is outside, so the means differ.no difference: 0difference C − A: (0.51; 3.19)

Why? The standard error of a difference, is smaller than the sum So the overlap check is too strict. The opposite does hold: if two 95 % intervals do not overlap at all, the difference is significant.

0.19Confidence intervals for other parameters

Every interval in the course follows the same recipe. Once you know the recipe, you only have to look up three things: the estimate, its standard error, and which distribution gives the critical value.

ParameterIntervalDistributionWhere in the course
mean above
difference Lecture 1
group mean in ANOVALecture 2
pair of groups, Tukeystudentized rangeLecture 2
proportion or an exact methodnormal, or binomialLecture 3
variance below
correlation through Fisher's then transform backnormalLecture 5
regression coefficient Lecture 6
Example

A proportion: 60 of 100 people prefer a product

The standard error is So gives

This simple formula needs a large sample, and it fails for small ones. For 2 of 10 it gives with a negative proportion, which is impossible. So R's binom.test uses an exact method based on the binomial distribution, which gives for 2 of 10. You saw this output in the sign test.

Example

A variance: the one-minute data

Here the quantity follows With 9 df, and and

So the CI for is Notice that the interval is not symmetric around because the chi-squared distribution is not symmetric. This one really needs normal data: the central limit theorem does not rescue it.

Watch out

A confidence interval is about a parameter, such as a mean. A prediction interval is about one new observation, and it is always wider. See Lecture 6.

0.20The idea of a statistical test

A test is like a court trial. The accused is presumed innocent until the evidence is strong enough. We start by assuming "nothing special is going on", and ask whether the data make that assumption hard to believe.

CourtStatistical test
Presumed innocent the null hypothesis: no effect
What the prosecutor claims the alternative hypothesis: there is an effect
EvidenceThe test statistic calculated from the data
"Beyond reasonable doubt"The significance level usually 0.05
GuiltyReject
Not guilty. This does not mean proved innocent!Do not reject This does not mean that is true!
Example

Is this coin fair? A test you can do by hand

You flip a coin 10 times and get 9 heads. the coin is fair, it is not,

  1. Assume is true. Then the number of heads follows
  2. How likely is a result this extreme or more?
  3. Count the other side too. 0 or 1 heads would be just as extreme, since is two-sided. So
  4. Decide. so reject . There is enough evidence that the coin is not fair.
00.10.2012345678910number of heads in 10 flips, if the coin is fairprobabilityobserved: 9just as extreme
If the coin is fair, the red outcomes happen in only 2.15 % of the cases. That number is the p-value.
R
binom.test(9, 10, p = 0.5)$p.value
[1] 0.02148438

That is the logic of every test in this course. Only the statistic changes. With 8 heads you would get so you would not reject. This is the same calculation as in the sign test.

0.21The p-value and your first t-test

Most test statistics have the same form. They ask: how far is the estimate from what claims, measured in standard errors?

The general form of a test statistic

A value near 0 agrees with A large value, positive or negative, speaks against

Example

One-sample t-test: did people guess 60 seconds on average?

against at

  1. Statistic: The mean is 2.65 standard errors below 60.
  2. Distribution under
  3. p-value: the area beyond ±2.654 is
  4. Decision: so reject People tend to guess too early.
00.10.20.30.4-5-4-3-2-1012345value of T if H₀ is truedensityT* = −2.65+2.65−2.26+2.260.01320.0132
The red area is the p-value, 0.0263. T* is beyond the critical values ±2.26. The 95 % CI (49.81; 59.19) does not contain 60. These are the three equivalent ways of deciding from Lecture 1.
Way to decideCheckResult
p-valuereject
critical valuereject
confidence intervalreject
In plain words

Why are they always the same? Rearrange the inequality: says " is further from than the margin of error". That is exactly the same as " is outside the interval". So a 95 % CI is the list of all the values of that the test at 5 % would not reject.

What the p-value is

The probability of getting a result at least as extreme as yours, if is true:

Sentence, for Why
"If were true, a result this extreme would happen about 3 % of the time."CorrectThis is the definition.
"There is a 3 % chance that is true."WrongThat would be Conditions cannot be swapped.
"There is a 97 % chance that is true."WrongSame mistake.
"The effect is large."WrongA small p-value can come from a tiny effect and a huge sample.
" is true."WrongWe just do not have enough evidence.

Statistically significant does not mean important

"Significant" only means "unlikely to be pure chance". Suppose a diet changes weight by 0.2 kg, with kg and 10,000 people in each group. Then and This is highly significant, but 0.2 kg is useless in practice. So report the effect size too, and a confidence interval is the best way to show it.

Errors and power

A test can be wrong in two ways. Type I: reject a true a false alarm, with probability Type II: fail to reject a false a missed effect, with probability Power is the chance of finding an effect that really exists. More data, a larger effect and less noise all raise the power. Lecture 1 covers this in detail.

Check yourselfA test gives with critical values ±2.0. What do you decide? Does the 95 % CI contain the value?

so do not reject By the equivalence, the 95 % CI does contain the value.

Check yourselfA 95 % CI for a difference is (0.2; 1.8). What do you know about the two-sided p-value of the test of 'no difference'?

0 is outside the interval, so

0.22Reading R's t-test output, line by line

R
t.test(x, mu = 60)

        One Sample t-test

data:  x
t = -2.6541, df = 9, p-value = 0.0263
alternative hypothesis: true mean is not equal to 60
95 percent confidence interval:
 49.81212 59.18788
sample estimates:
mean of x
     54.5
LineMeaning
t = -2.6541The test statistic The mean is 2.65 standard errors below 60.
df = 9Degrees of freedom, It tells you that
p-value = 0.0263Below 0.05, so reject
alternative hypothesisWhat was. Always check that this is what you meant. "Not equal" means two-sided.
95 percent confidence intervalThe CI for the mean. The value 60 is outside it, so reject.
mean of xThe estimate
In plain words

Get the standard error back from any such output:

0.23The distributions you will meet

You do not need to memorize their formulas. Know what each one is for, what it looks like, and where it comes from.

Normal N(μ, σ²)
-4-2024
Student t(d)
-4-2024
Chi-squared χ²(d)
051015
Fisher F(d₁, d₂)
012345
Binomial Bin(n, p)
0510
Exponential Ex(λ)
012345
DistributionWhat it describesWhere you use itR name
Normal Measurements, errors, and means of large sampleseverywherenorm
Student Normal, divided by an estimate of its SDmeans, differences, regression coefficientst
Chi-squared A sum of squares of standard normals. Never negative.variances, goodness of fit, Kruskal-Wallischisq
Fisher A ratio of two variances. Never negative.ANOVA, overall test of regressionf
Binomial Number of successes in triessign test, goodness of fitbinom
Poisson Number of rare events in a fixed timegoodness of fitpois
Exponential Waiting timesgoodness of fitexp
UniformAll values equally likelyrandom numbersunif

The first four are one family, built from the normal one step at a time. Lecture 1 builds each of them from the same small sample.

0.24Are you ready for Lecture 1?

Try to answer each question out loud before you open the answer. If one is hard, go back to its topic. Lecture 1 will then feel like revision.

Check yourselfWhat is the difference between and

is the true population mean: fixed and unknown. is the mean of your sample: known, but it changes from sample to sample.

Check yourselfWhat is the difference between standard deviation and standard error?

The SD says how much individuals differ, and it does not shrink with more data. The SE, says how much the sample mean would change between samples, and it shrinks as grows.

Check yourselfWhat does the central limit theorem say, and why do we care?

The mean of many independent values is approximately normal, whatever the original distribution was. So methods for means work even if the data are not exactly normal.

Check yourselfWrite the general form of a confidence interval. What does 95 % refer to?

Estimate ± critical value × standard error. The 95 % is the share of samples for which this method catches the true value.

Check yourselfWhat happens to a CI if you raise the confidence from 95 % to 99 %? And if you quadruple

A higher confidence makes it wider. Quadrupling makes it about half as wide.

Check yourselfDefine the p-value in one sentence.

The probability of a result at least as extreme as yours, assuming is true.

Check yourselfYou get What do you write?

"We do not reject " You never write that is true.

Check yourselfA two-sided test at 5 % rejects Can the 95 % CI contain 10?

No. The two always agree, so 10 must be outside the interval.

Lecture 1 · 15 September 2026

Introduction: the foundations

This lecture repeats what you need for the rest of the course. The lecturer said it contains no new topic, but the whole semester depends on it.

In plain words

New to statistics? "Repeats" means that it moves fast and assumes a first course. Read Statistics from zero first, especially the sampling distribution, confidence intervals and the idea of a test.

1.1Probability, statistics and machine learning

These three words are often mixed. Here is the difference.

Probability theoryMathematical statisticsMachine / statistical learning
Starts fromdefinitions and axiomsa sample of real dataa large amount of real data
Doesgives definitions, theorems and proofs for working with random eventscollects, organizes, analyzes, interprets and presents data; fits models, estimates parameters, tests hypothesesfinds patterns and makes predictions, often with heuristic methods
Says how precise it is?no real data hereyes, alwaysusually not

Czech names: probability theory teorie pravděpodobnosti, mathematical statistics matematická statistika, machine / statistical learning strojové / statistické učení.

Statistics is never about perfect data. If you have perfect data, you need the probability, not the statistics. Statistics is about imperfect data: how to gain information, not perfect but approximate information, from approximate data.

Lecturer L1 38:23

If you say 3 kilograms, it's almost useless information in statistics. If you add the information, it is 3 kilograms with standard deviation of 100 grams, this is a proper statistical result.

Lecturer L1 41:05
In plain words

A statistical result has two parts: a guess and how precise the guess is. The lecturer's example: people ate on average 3 kg of chocolate last year. "3 kg ± 0.1 kg" is useful. "3 kg ± 3 kg" tells you almost nothing.

1.2The three kinds of statistical work

KindWhat it doesTypical tools
Descriptive statistics popisná statistikaSummarizes the sample with numbers.frequency tables; moments (mean, variance, standard deviation, skewness, kurtosis); quantiles (median, quartiles, IQR); contingency tables; sample correlation
Exploratory data analysis (EDA) exploratorní analýza datLooks at the data, usually with pictures.frequency plot, boxplot, histogram, scatter plot, QQ plot
Statistical inference statistická inferenceSays something about the whole population from a small sample. It needs a model: assumptions about the population and the sample.point and interval estimates (confidence intervals), prediction, classification, clustering, hypothesis tests

Doing statistical inference without looking at the data is a bad practice. Every time you load new data, before you do anything else, you should do these two things very quickly: make some tables, make some typical visualizations. You should know your data.

Lecturer L1 43:50

1.3Parametric, nonparametric, semiparametric

Statistical inference has three families of methods.

FamilyAssumptionExamplesTrade-off
ParametricThe data come from a known family of distributions (for example normal). We estimate its parameters.t-test, ANOVA, linear and multiple regression, generalized linear models, correlation analysisEasy to compute and explain, but with strict assumptions
NonparametricVery few assumptions. No specific distribution is needed.rank statistics and rank tests, nonparametric ANOVA, rank correlations, functional data analysisUsable almost everywhere, but often less power
SemiparametricA mix of both.Cox proportional hazards model in survival analysisNot covered in this course

The parametric methods are relatively easy to calculate and to interpret. Everybody likes them, but they have relatively strict assumptions. And in reality, unfortunately, many people are using methods which should not be used. You should be sure that you understand the assumptions of each method.

Lecturer L1 45:44

1.4Statistical data types

Stevens (1946) sorted data into four levels. Each level allows everything from the level before it, plus something new.

LevelAllowed operationsTypeIn RExamples
Nominal nominální belongs to a setcategorical, discretefactorblood type, gender, region
Ordinal ordinálníalso order: sorting. Distances have no meaning.categorical, discreteordered factorhighest education, grades, competition ranking
Interval intervalováalso distance: Ratios have no meaning because zero is not fixed.numeric, typically continuousnumeric, integertemperature in °C, calendar year
Ratio poměrováalso Zero and scale are fixed.numeric, typically continuousnumeric, integertemperature in K, mass, length, duration

Two special kinds of nominal data:

  • Dichotomous data: only 2 categories, often FALSE and TRUE.
  • Dummy variable: the numbers 1 and 0 show membership in a category. You need it later for regression, because matrices can only hold numbers.

The temperature expressed in degrees of Celsius does not have a fixed zero. If you say that today is two times higher temperature than yesterday, if it means that today it is 20 degrees Celsius and yesterday it was 10 degrees Celsius, this is not correct. If you say the same in Kelvins, you are correct.

Lecturer L1 53:19

Another typical example is the calendar year. Do you remember that there is no year zero?

Lecturer L1 54:16

Two more notes: you need to know the meaning of the data (the variables, the experiment, the preprocessing) to choose the type. And continuous data can be turned into ordered categories by sorting them into intervals, with some loss of information.

If you miss this, your statistical analysis will be completely incorrect, because the proper assignment of the statistical data types is saying to the functions what they should do with the data.

Lecturer L1 69:07

Discrete or continuous

This second classification asks if you can count the possible values.

  • Discrete: the values can be listed: finitely or countably many, often integers. Examples: gender, blood type, grades, ranking, number of children.
  • Continuous: uncountably many values, typically a whole interval, and arbitrarily precise. This applies to interval and ratio data. Examples: height, weight, time.
Check yourselfWhich level is each one? (a) shoe brand, (b) exam grade A to F, (c) year of birth, (d) body weight.

(a) nominal, (b) ordinal, (c) interval (no real zero), (d) ratio. 80 kg really is twice 40 kg.

1.5Tidy data and the tidyverse

A table is tidy data (Hadley Wickham, 2014) when:

  • every column is a variable, with one unique meaning;
  • every row is an observation (one case);
  • every cell is a single value. (Newer "nested data" allows a column that holds lists or smaller tables.)

The goal: "Spend less time fighting with the tools and more time working on your analysis." In R a table is a data.frame (old and widely compatible) or a tibble, also written tbl_df (the modern version). All tidyverse functions expect tidy tables.

Everything should be a table. To be really correct, even if you have only one observation, it should be a table with one row and one column.

Lecturer L1 58:05

The tidyverse (2016) is a collection of libraries for data science that share one philosophy, one consistent syntax, and work well together. The pipe |&gt; or %&gt;% makes code read like a sentence.

LibraryJobLibraryJob
dplyrmanipulate data: filter, sort, group, summarizetibblemodern data frames
tidyrreshape and tidystringrstrings
ggplot2graphics (grammar of graphics)forcatscategorical variables (factors)
readrfast import of CSV, TSV and so onlubridatedates and times
purrrfunctional programming with functions and lists

In classical, modern statistical data analysis, you should completely avoid writing loops, because everything can be nowadays done without loops.

Lecturer L1 70:27

dplyr and tidyr verbs

These work almost like SQL.

You want toUse
create or load a tabledata.frame, tibble, expand_grid, read.*
change or add columnsmutate, mutate(across), transmute, rename
choose columnsselect, pull
choose rowsfilter, slice
sort rowsarrange
split into subtablesgroup_by
calculate summariessummarise, summarise(across)
switch wide and long formatpivot_longer, pivot_wider
join two tablesleft_join, right_join, full_join, cross_join, semi_join, anti_join

ggplot2

You declare what you want in four steps: give tidy data, map columns to aesthetics with aes (x-axis, y-axis, grouping, line type, color, background, symbol), say which shapes to draw, then adjust details. Start with ggplot and add layers with +.

  • Simple shapes: geom_line, geom_point, geom_jitter.
  • Statistical shapes: geom_boxplot, geom_histogram, geom_density, geom_bar, geom_ribbon, geom_qq, geom_qq_line, geom_rug, geom_area.

This will be the minimum accepted graphics for you. We will really not accept any graphics in basic R.

Lecturer L1 63:03

1.6The running example: weight loss on three diets

78 people followed diet A, B or C for 6 weeks. The lectures keep coming back to these data.

R
str(data)   # or: glimpse(data)
'data.frame': 78 obs. of 7 variables:
 $ Person      : int  25 26 1 2 3 4 5 6 7 8 ...
 $ Gender      : int  NA NA 0 0 0 0 0 0 0 0 ...
 $ Age         : int  41 32 22 46 55 33 50 50 37 28 ...
 $ Height      : int  171 174 159 192 170 171 170 201 174 176 ...
 $ WeightPrev  : int  60 103 58 60 64 64 65 66 67 69 ...
 $ Diet        : int  2 2 1 1 1 1 1 1 1 1 ...
 $ Weight6Weeks: num  60 103 54.2 54 63.3 61.1 62.2 64 65 60.5 ...

# Add the weight loss, and give Diet and Gender their proper statistical type
data <- data |>
  mutate(
    WeightLoss = WeightPrev - Weight6Weeks,
    Diet = factor(Diet, labels = c("A", "B", "C")),
    Gender = factor(Gender, labels = c("Female", "Male"))
  )
In plain words

Look at what str shows first: Diet is stored as the integer 1, 2 or 3. R would treat it as a number and could calculate the "average diet", which is nonsense. factor() tells R that it is a label. The first row of the table is person 25, a woman or man we do not know (NA), with diet B and a loss of 0 kg.

This is a local work inside a tidy table. There's an expression on the right hand side, and the result is stored into a column with the name on the left hand side. If the column does not exist, it is automatically created. If it already exists, it is rewritten.

Lecturer L1 68:00

Descriptive statistics by group

R
data |>
  group_by(Diet) |>
  summarise(size = n(), mean = mean(WeightLoss), st.dev = sd(WeightLoss),
            variance = var(WeightLoss), median = median(WeightLoss))
Dietsizemeanst.devvariancemedian
A243.302.245.023.05
B273.032.526.373.30
C275.152.405.745.40

Diet C looks better: about 2 kg more. Is that a real effect or just luck? Tests answer this question.

Barplot: how many people per diet.
Boxplot with the individual points added (geom_jitter). Diet C sits higher.

Everybody should understand or remember what is a box plot. [The middle line is the] median. [The box edges are the] so-called quartiles. How many of the observations are inside the box? 50% of the data.

Lecturer L1 73:54

1.7Random variable and probability distribution

A random variable náhodná veličina is a measurable mapping from the space of elementary events to the real numbers. A realization (or observed value) is the value that really happened in the experiment.

In plain words

A random variable is a translator between the real world and numbers. "It is 15 °C now and not raining" is a sentence, and mathematics cannot calculate with sentences. The random variable gives each outcome a number. Capital means the variable before you measure. Small means the number you got.

It's a connection between the space of outcomes of some experiment in the real world and the world of numbers. To be able to use any part of mathematics, we must transform everything into numbers.

Lecturer L1 76:42

A probability distribution rozdělení pravděpodobnosti assigns a probability to each event (each set of values). It describes the type of randomness of the phenomenon.

Distributions come in two groups:

DiscreteContinuous
Valuesat most countably many points on the lineuncountably many values, an interval
Used forcategorical and numerical datatypically numerical data
NamesBernoulli (alternative), binomial, geometric, hypergeometric, Poisson, negative binomialcontinuous uniform, Gaussian (normal), chi-squared, Student t, Fisher-Snedecor F, exponential, Weibull, lognormal, logistic, Pareto, gamma, beta

1.8Random sample and independence

A random sample náhodný výběr of size (also called i.i.d., independent and identically distributed) is a random vector where the variables

  • have the same probability distribution and
  • are mutually independent.
Independence

Stochastic independence stochastická nezávislost means:

This is a cornerstone of classic statistics. Classic methods assume that your data form a random sample.

It is not the independence that we have done something independently, as we are typically saying. [It] has a precise definition given by the probability theory, and the definition is very strict.

Lecturer L1 80:08

Therefore it is very difficult to be tested. In fact, we have no general statistical method to test independence, because it is about the origins of the whole theory.

Lecturer L1 81:24

1.9Normal distribution and standardization

From here on, we build the whole family of distributions from one simulated example: 5 values from

Standardization

Subtract the mean, divide by the standard deviation. The result is the standard normal distribution, with mean 0 and variance 1.

Y ~ N(3, 2²), the original valuesZ ~ N(0, 1), the standardized values
00.10.20.30.4-6-4-20246810xdensityq₀.₉₅ of Z = 1.64q₀.₉₅ of Y = 6.29
The same data before and after standardization. Dashed lines are the 95 % quantiles. Standardizing moves the centre to 0 and rescales the width to 1.

Every time you will hear about standardization, it always means: take your data, separately each observation, minus mean, divided by standard deviation.

Lecturer L1 83:43

Common questions, answered

  • What is the probability density function (PDF)? A function whose total area is 1:
  • Where is the probability on the density plot? Probability is an area under the curve, not the height of the curve.
  • What is a histogram? A picture of real data: split the axis into bins and draw a bar for each one. With the density scale, the bars have total area 1, so it estimates the PDF.
  • What is the 95 % quantile The number with 95 % of the probability on its left:
  • How do you find it on the plot? Find the place on the x-axis where the area to the left is 0.95.
00.10.20.30.4-3-2-10123xdensity95 % quantilearea = 0.95area = 0.05
The 95 % quantile splits the area under the density into 0.95 on the left and 0.05 on the right.

If you said that both areas are equal to one, I hope everybody can see that the red area is much bigger than the yellow area. But you must look at the scale. It is mandatory: each mathematical plot must have the scales on the axis.

Lecturer L1 86:06

1.10Chi-squared distribution and degrees of freedom

Step 1. Standardize each value, square it, and add everything up.

Chi-squared with n degrees of freedom

Step 2. In practice we do not know Replace it with its unbiased estimator, the sample mean

With estimated mean: one degree of freedom is lost

Why

The sample mean is itself a random variable, because it comes from the random sample. It also creates one constraint:

In plain words

Degrees of freedom count how many values are free to change. Suppose 3 numbers have mean 10, and you know the first two: 8 and 13. The third must be 9. You chose only 2 numbers freely. So once the mean is fixed, one value has no freedom left.

Because we are using the data twice: once inside this square, and second time to calculate this sum. You are using the same information in different ways. And in statistics, you cannot do this without changing the degrees of freedom. Every time you use the estimated mean, the sample mean, the average, you are losing one degree of freedom.

Lecturer L1 90:40
W ~ χ²(5): true mean μ is knownV ~ χ²(4): μ replaced by the sample mean
00.050.10.150.2024681012141618xdensity9.4911.07 (95 % quantiles)
The curves look similar, but the 95 % quantiles differ a lot: 11.07 and 9.49. Using the wrong one gives a wrong test.

In statistics, most of the work is done via the quantiles. Maybe the shapes are similar. It depends on the point of view. But these two numbers are very different. You cannot say that instead of this quantile, you will use this quantile. If you do this, you are saying completely incorrect results.

Lecturer L1 93:41
Check yourselfWhy does have degrees of freedom, and not

Because we replaced with the sample mean. The deviations from the sample mean must sum to 0, so that is one constraint. Once deviations are known, the last one is fixed.

1.11From the normal distribution to Student's t

Step 1. Now only center the values, and add them:

Why? A sum of independent normal variables is normal. Means add: Variances add:

Step 2. Standardize divide by its standard deviation

This is the formula of the Z test: it tests a mean when you know

Step 3. We rarely know Use the sample standard deviation:

is a random variable, because it depends on the sample. So the result is no longer normal:

The t statistic

A standard normal variable divided by the square root of (chi-squared / its degrees of freedom) has Student's t distribution by definition.

There is no magic. It's only some work. Put everything from the previous [steps] together until you obtain this final, so-called t statistics. This is exactly how the test is working. In fact, this is almost the whole mathematical proof.

Lecturer L1 97:16
Z ~ N(0, 1): σ is knownT ~ t(4): σ estimated by S
00.10.20.30.4-5-4-3-2-1012345xdensity1.642.13 (95 % quantiles)
Student's t has heavier tails than the normal: extra uncertainty, because σ was estimated. The t distribution here has 4 degrees of freedom. As the sample grows, it approaches the normal.
In plain words

The chain to remember:

  • Normal, then standardize: N(0, 1).
  • Square and add standard normals: χ².
  • Normal divided by the root of (χ²/df): t.
  • Ratio of two independent (χ²/df): F, which you meet in Lecture 2.

You should at least remember that you know normal distribution, standardized distribution, chi-square distribution, Student t distribution and Fisher distribution.

Lecturer L1 98:07

1.12Cumulative distribution function

The CDF gives the probability of being at most It goes from 0 to 1 and never decreases.

  • From PDF to CDF: is the area under the density to the left of So
  • From CDF to quantile: the quantile reverses the CDF. Pick a probability on the y-axis, read on the x-axis.
Density f(x): probability is an area
00.10.20.30.4-202xf(x)x = 1area 0.84
CDF F(x): the same area, read as a height
00.250.50.751-202xF(x)F(1) = 0.84
The same probability shown two ways. The area on the left equals the height on the right.

Plotting the CDFs of all six variables together shows an important message: you must understand the correct type of distribution of a random variable, because each one has a different curve and different quantiles.

CDFs of all six variables: Y, U (standardized), W, V, Z and T.
Watch out

Be careful with the definition. This course uses The lecturer warned that some sources, including the web page he linked, use a different definition of the CDF. Older Czech books often use

There is one important note: they are using a different mathematical definition of the CDF, in Czech the distribution function. Be very careful.

Lecturer L1 34:31

1.13Is my data normal? Histogram and Q-Q plot

Back to the diet data.

Histograms per diet with facet_grid. Look for symmetry and one peak.
Q-Q plots per diet. Points close to the line mean roughly normal data.
R
data |> ggplot(aes(x = WeightLoss, fill = Diet, color = Diet)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 2, linewidth = 0.3,
                 color = "black", alpha = 0.7) +
  labs(x = "Weight Loss / kg", y = "density") +
  facet_grid(Diet ~ .)

data |> ggplot(aes(sample = WeightLoss, color = Diet)) +
  geom_qq(distribution = qnorm, size = 2.5) +
  geom_qq_line(distribution = qnorm, linewidth = 0.7, color = "black") +
  labs(x = "theoretical quantiles of N distribution", y = "sample quantiles") +
  facet_grid(. ~ Diet)
In plain words

A Q-Q plot compares your sorted data with the values you would expect from a normal distribution. If the data are normal, the points lie on a straight line. Curved ends mean the tails are different from normal.

1.14Hypotheses and decisions

The history: Pearson, Gosset and Fisher started significance testing around 1900. Neyman and Pearson (1933) created the modern theory.

A statistical hypothesis is a pair of statements:

  • the null hypothesis nulová hypotéza: the statement being tested. Often "no effect" or "no difference", but not only.
  • the alternative hypothesis alternativní hypotéza: the statement tested against Usually "there is an effect".

A statistical test is a decision based on a random sample. There are exactly two results:

  • the test rejects zamítá in favor of or
  • the test does not reject (fails to reject) nezamítá in favor of

The general theory is the Neyman-Pearson lemma. A good criterion for choosing hypotheses is a likelihood ratio.

Watch out

Never write " is true". Not rejecting means only that the sample has no strong evidence against In exams and reports, write "we do not reject ".

Remember that you cannot say that null hypothesis is true. This is a question which can never be answered in statistics. You should never say that something is true or is not true.

Lecturer L1a 20:04
Check yourselfA test gives Can you write that is true?

No. Write that we do not reject The sample has no strong evidence against it, but the effect could still exist and be too small, or the sample could be too small.

1.15Four outcomes and two errors

The test makes the decision, but nobody knows the truth. So four situations are possible.

Test decisionTruth: is trueTruth: is true
rejects True Positive: correct detection
(the power)
False Positive = Type I error: false alarm
does not reject False Negative = Type II error: missed detection
True Negative: no action, correct
In plain words

Think of a fire alarm. Type I: the alarm rings, but there is no fire. Type II: there is a fire, but the alarm stays silent.

We can only assume whether null hypothesis or alternative hypothesis is true. But if it happens that in fact the null hypothesis is true, but the test, which based its decision on the random sample, decides to reject the null hypothesis, it is so-called type one error. In natural language, it is typically called a false alarm.

Lecturer L1a 5:21

This is typically a situation where there is some change, but the change is so small or the sample size is so small that the test cannot find enough statistical evidence to reject the null hypothesis.

Lecturer L1a 6:18
Check yourselfA test says that a diet works, but in truth it does nothing. Which error is this?

A Type I error (false positive, false alarm). Its probability is

1.16The Neyman-Pearson rules

  • No test can make and You cannot even make both as small as possible at once.
  • The significance level hladina významnosti must be fixed before the test, independently of the sample size and of
  • The power síla of the test is
  • Tests are built so that and the power is as large as possible (uniformly most powerful tests at level
  • Power depends strongly on the sample size, effect size and variability of the data. It increases when the sample size and effect size increase. This topic is called power analysis.

It is a general agreement of most of the statisticians and the data analysts around the world that the typical value of alpha, if you do not have a special need, is 5%. So in all our course we will use alpha equal to 0.05. This must be fixed before performing the statistical test.

Lecturer L1a 9:00

1.17Way 1: testing with a p-value

  1. State and from the research question.
  2. Check the assumptions about the data and choose a test, with a test statistic whose distribution under is known.
  3. Choose typically
  4. Calculate the observed value of the statistic.
  5. Calculate the p-value
  6. If reject in favor of
p-value

The p-value p-hodnota is the probability, assuming is true, that the statistic takes a value as extreme as or more extreme than the observed It is the smallest at which would be rejected.

  • The p-value is used only to decide: reject or do not reject.
  • It does not measure practical significance or effect size.
  • It is not the probability that is true:
In plain words

Imagine there really is no effect. How surprising would your data be? A small p-value means "data like this would be very rare if were true", so we stop believing

If you will repeat the same statistical test under exactly the same conditions, but using a different random sample of the same sample size, the p-value is the probability that the new fictive sample will be similar or more extreme than your current sample.

Lecturer L1a 15:22

It should be used only as specified in the last point of the methodology. Remember that the p-value does not measure the significance or effect size, and also the p-value is not a probability that the null hypothesis is true. It is a relatively complicated concept which was developed to be easy as a decision making tool.

Lecturer L1a 17:33
Example

Shapiro-Wilk normality test on the diets

the sample follows a normal distribution. it does not.

R
data |> summarise(.by = Diet, SW_p = shapiro.test(WeightLoss)$p.value)
  Diet       SW_p
1    B 0.96117485
2    A 0.07748634
3    C 0.37204003

All three p-values are above 0.05, so for each group we do not reject . The data give no evidence against normality. We still do not say "the data are normal".

Check yourselfYou get What do you decide at And at

At 0.05 you reject because At 0.01 you do not reject it. This is why must be fixed before the test.

1.18Way 2: testing with a critical region

Steps 1 to 4 stay the same. Then:

  1. Set up the critical region
  2. If reject in favor of

The critical region kritická oblast is the set of values of that lead to rejection. It depends on and on and it ensures Its limits are quantiles of the distribution of under

AlternativeCritical region
two-sided
one-sided, lower
one-sided, upper

In fact this is the original testing procedure which you can find in relatively old mathematical papers. The intervals are bounded by quantiles of the probability distributions. Therefore the quantiles are almost everywhere used in the background of statistical testing.

Lecturer L1a 21:17

1.19Way 3: testing with a confidence interval

This works when the hypotheses can be written with a parameter Let be its value under Then:

  1. Calculate the confidence interval (CI) for matching
  2. If reject in favor of

A confidence interval interval spolehlivosti is a range of values for computed from the data, that contains the true value with the given probability typically 95 %. It depends on (one or two sides) and on the confidence level.

Watch out

That probability describes the method, before you have the data: about 95 % of such intervals catch the true value. Once you have your numbers, the interval either contains or it does not. See what "95 % confident" really means.

In plain words

Why this test works: a 95 % interval is the list of all values of that a test at 5 % would not reject. So " is outside the interval" and "reject " are one and the same statement. The formulas and the step-by-step construction are in Statistics from zero.

If you are able to calculate the confidence interval, and in R it is relatively easy, the functions which provide the statistical tests typically report the p-value and the confidence intervals. So it is only about reading the bounds.

Lecturer L1a 24:21

In some cases there is even no way to calculate the confidence interval, because this last possibility of statistical testing requires that your null and alternative hypothesis can be expressed by using some parameter.

Lecturer L1a 26:25

Typically under null hypothesis the value of the parameter is equal to zero. No change means zero change. Therefore the title null hypothesis.

Lecturer L1a 25:13

All the three possible methodologies for the decision in the statistical test are completely equivalent. All three ways always lead to the same decision.

Lecturer L1a 35:51

1.20Two-sample t-test on the diets

Two-sample Student's t-test

Two independent random samples of sizes from normal distributions with means

and or one of the one-sided versions.

  • Equal variances: is the scaled pooled variance and
  • Unequal variances: Welch's t-test, with an unbiased estimator of the variance and a special formula for

Here is what those two phrases mean. is the standard error of the difference so is again signal divided by noise.

Equal variances (pooled)Unequal variances (Welch)
Standard error with
Degrees of freedom usually not a whole number
In Rt.test(..., var.equal = TRUE)t.test(...), the default
In plain words

is a weighted average of the two sample variances, with larger samples counting more. The degrees of freedom add up because each sample loses one for its own mean.

Compare diets A and C. A reasonable hypothesis: against

Boxplots of diets A and C.
Example

The Welch t statistic by hand

From the table: and

This is the same value that R reports below. The degrees of freedom also come from the Welch formula:

R
t.test(WeightLoss ~ Diet, data = data |> filter(Diet != "B"), alternative = "two.sided")
        Welch Two Sample t-test
data:  WeightLoss by Diet
t = -2.8462, df = 48.862, p-value = 0.00645
alternative hypothesis: true difference in means between group A and group C is not equal to 0
95 percent confidence interval:
 -3.1531357 -0.5431606
sample estimates:
mean in group A mean in group C
       3.300000        5.148148

Unfortunately the relatively old functions are not prepared for direct using the tidyverse syntax. So in such cases, we will slightly mix the base syntax with the tidyverse syntax.

Lecturer L1a 31:23

The same decision, three ways

WayReadingDecision
p-valuereject
Confidence intervalParameter: Under it equals 0. CI is and 0 is outside.reject
Critical region qt(c(0.025, 0.975), df = 48.862) gives is inside the region.reject
00.10.20.30.4-4-3-2-101234value of the test statistic T under H₀density−2.01+2.01T* = −2.85rejectrejectdo not reject
Two-sided test: the observed value T* falls in the left rejection region.
Example

Where the interval (−3.15; −0.54) comes from

R gives only the two limits. By hand: estimate ± critical value × standard error.

In words: with 95 % confidence, diet C loses between 0.54 and 3.15 kg more than diet A on average. A p-value could not tell you that size. The full explanation is in Comparing two groups.

We are asking whether the value t-star belongs to the critical region, whether it belongs to the two intervals which are shaded on this plot. The answer is yes. And because the t-star value belongs to the critical region, the decision is: reject the null hypothesis.

Lecturer L1a 39:29

1.21One-sided tests

Reasonable one: (diet A loses less than diet C).

R
t.test(WeightLoss ~ Diet, data = data |> filter(Diet != "B"), alternative = "less")
t = -2.8462, df = 48.862, p-value = 0.003225
alternative hypothesis: true difference in means between group A and group C is less than 0
95 percent confidence interval:
       -Inf -0.75944
qt(0.05, df = 48.862)
[1] -1.676642
00.10.20.30.4-4-3-2-101234value of the test statistic T under H₀density−1.68T* = −2.85rejectdo not reject
H₁: μA < μC. All of α sits in the left tail. T* = −2.85 is below −1.68, so we reject H₀.

Unrealistic one: The boxplots already show that A is not higher.

R
t.test(WeightLoss ~ Diet, data = data |> filter(Diet != "B"), alternative = "greater")
t = -2.8462, df = 48.862, p-value = 0.9968
95 percent confidence interval:
 -2.936856       Inf
qt(0.95, df = 48.862)
[1] 1.676642
00.10.20.30.4-4-3-2-101234value of the test statistic T under H₀density+1.68T* = −2.85rejectdo not reject
H₁: μA > μC. T* is far away from the rejection region on the right.
-4-3-2-101difference in means μA − μC (kg)H₀ value: 0H₁: μA ≠ μC, CI (−3.15; −0.54): 0 is outside, rejectH₁: μA < μC, CI (−∞; −0.76): 0 is outside, rejectH₁: μA > μC, CI (−2.94; +∞): 0 is inside, do not reject
The three confidence intervals together. The orange dot is the estimated difference, −1.85. One-sided intervals are open on one side.

Why is one limit infinite? A one-sided test looks in one direction only, so it needs a limit on one side only. All of goes into one tail, which is why the critical value is instead of For the upper limit is

Is this even a realistic hypothesis? No. A p-value near 1 is a warning sign that your points the wrong way.

If it happens that the p-value is almost 1, very close to 1, this is typically an indicator that you tried to test a pair of statements which really do not agree with the sample. You should go back and check whether you are asking even a reasonable question.

Lecturer L1a 42:54

If you ask a stupid question, you will of course obtain a stupid answer, a stupid decision. The test cannot do anything else. So this is one of the reasons why you should never say that null hypothesis is true.

Lecturer L1a 45:14
Watch out

Note this example well. In the last test we did not reject although the earlier tests clearly rejected it. It shows why "not rejected" does not mean "true".

Check yourselfWhy is the p-value of the test with (0.003225) half of the two-sided one (0.00645)?

The two-sided p-value counts both tails, so it doubles the smaller tail. The one-sided test uses only one tail, and lies on the side that predicts.

1.22Significance level and power

Draw two curves: the distribution of under and under a specific For the two-sample test, the curve is a non-central t distribution. As an example, take and

  • is the area beyond the critical value under the curve.
  • (power) is the area over the same interval under the curve.

Move α down from 0.05 to 0.01 (for example). The critical value moves left and both areas shrink. Now increase the effect size: power rises while α stays the same.

To understand that in most cases making the significance level alpha lower is not a good idea. Because if you do this, you are saying that you like to be more strict in the type one error, but this automatically means that your test will have a lower power. So statistical testing is somehow a compromise between the type one and type two error.

Lecturer L1a 51:30

1.23The multiple testing problem

Suppose you have 3 independent normal samples with the same variance. You want to test against at least two means differ. Can you use two-sample t-tests?

  • You can, in a naive way. For 3 groups you need 3 tests: A-B, A-C, B-C.
  • But each test has a 5 % risk of a false alarm, and the risks add up.
Familywise error rate

The probability of at least one Type I error in tests, each at level

Why? One test has no false alarm with probability All tests have none with probability if we treat them as independent. "At least one" is the opposite event.

groups tests
210.05
330.14
460.26
5100.40

You can naively use three times two-sample t-tests. But your overall probability of type one error is about 14%. And in practice, nobody will use your procedure. 5% is a typical way for allowing the type one error, but 14% is really too much.

Lecturer L1a 54:47

So for comparing three or more groups, we must find something smart, something not so naive. This will be a starting point for the next week, where we will speak about the idea developed by Sir Fisher called Analysis of Variance.

Lecturer L1a 55:52

Fisher's different approach (1918, 1921, 1925) is analysis of variance (ANOVA) analýza rozptylu, the topic of Lecture 2.

Check yourselfWith 6 groups and how many pairwise tests do you need, and what is the familywise error rate?

tests. That is more than a 50 % chance of at least one false alarm.

Lecture 2 · 22 September 2026

Analysis of variance (ANOVA)

How do you compare the means of three or more groups with one test, and keep the false alarm risk at 5 %?

Going back to the data about the people in three groups, we want to test that three means are the same against the alternative that at least two of them are different. And we would like to do this using only one statistical test.

Lecturer L2 3:51
In plain words

You will need: variance and the sum of squares, the multiple testing problem, how a test works and confidence intervals. The whole method rests on one sentence: split the total variability into a part between groups and a part inside groups.

2.1The problem and the correct procedure

Data: weight loss in kg after 6 weeks under 3 diets.

Left: all people together. Right: split by diet. The groups seem to differ, mostly because of diet C.

the means of weight loss are the same for diets A, B and C. at least two diets have significantly different means.

  • Naive idea: 3 pairwise t-tests at 5 %. The familywise error rate becomes
  • Correct procedure: (1) one omnibus test, then (2) post-hoc tests, only if the omnibus was rejected.

The problem is not that this is not correct. From the first point of view, it is not forbidden. But statistical testing is never perfect. You must report the family-wise error, to really say how realistic your conclusion is. If you publish such a result, nobody will use your result.

Lecturer L2 9:38
In plain words

The boxplot shows medians, but ANOVA compares means. Why can you still guess the result from a boxplot? When a distribution is symmetric, the mean and median are the same. So if the boxes look symmetric, the medians show you roughly where the means are.

2.2One-way ANOVA: setting and notation

In one-way ANOVA jednofaktorová analýza rozptylu / jednoduché třídění:

the expected values of the response are equal in all groups. at least two groups have different expected values.

  • Fisher (1918): variance as a useful statistical tool. Fisher (1921): ANOVA. It became widely used after his book of 1925.
  • ANOVA generalizes the two-sample t-test to 3 or more independent groups.
  • ANOVA guarantees the familywise error rate, because it is one test.

Notation:

groupobservationssizesample meanassumed distribution
1
  • is the -th observation in the -th group. So is person 10 in group 3.
  • Group sample mean:
  • Total sample size:
  • Overall sample mean:
In plain words

The dot means "over all values of this index". means the average over all people in group 3. means the average over all groups and all people.

Tidy data for ANOVA needs only two columns: a numeric response and a nominal grouping variable of type factor with levels. Other columns may stay in the table.

2.3Three ways to write the same model

1. Cell means model

against there exist with Here is the group mean skupinový průměr and are the random errors náhodné chyby. The unbiased estimator of is

The assumptions of ANOVA
  1. The observations are mutually independent.
  2. Random errors follow the normal distribution,
  3. The variance is homogeneous: the same for all observations in all groups.

Whether the observations are independent or not depends on the design of the experiment. After you have the data, you are not able to change it.

Lecturer L2 30:16

2. Factor effects model (the one used in practice)

against there exists with

  • is the grand mean celkový průměr, the group mean, and is the effect efekt of group
  • Estimators: and
  • Identification constraint:
In plain words

An effect says how far a group is from the overall average. "Diet C has an effect of +1.3" means that it loses 1.3 kg more than average. The hypothesis also becomes simpler: "at least one effect is not zero".

Check yourselfWhy do we need the identification constraint?

There are groups, but parameters on the right: one and effects. It is like having equations with unknowns: infinitely many solutions. One extra equation makes the solution unique. Weighting by makes exactly the overall mean.

If there is more than one solution, it is nice in pure mathematics, but not useful in statistics. So we need to be sure that it has exactly one solution. To go back to the uniqueness, we need to add one special equation.

Lecturer L2 38:31

3. Reference group model (what software uses inside)

against there exists with Also called treatment contrasts. The three models connect like this:

  • One group is the reference, and other groups are compared with it. is the mean of the reference group, reported as (Intercept). is reported as a coefficient.
  • Exactly parameters, so no extra constraint is needed.
  • R, Python, Stata: the reference is the first level. SPSS, SAS: the last level.
Example

Three tables, same data

Read each table and connect them.

R
model.tables(anova_model, type = "means")
Grand mean 3.844872
        A     B     C
      3.3 3.026 5.148
rep  24.0 27.000 27.000
model.tables(anova_model, type = "effects")
           A       B     C
     -0.5449 -0.8189 1.303
coefficients(anova_model)
(Intercept)      DietB      DietC
  3.3000000 -0.2740741  1.8481481
  • Effect of A: Effect of C:
  • Constraint check: ✓
  • Reference is A, so the Intercept is DietC: DietB:

2.4The key idea: splitting the variability

Think about the title of the method. It is called analysis of variance, but the task is to compare the means. So the title is saying that in the background, the mathematics is completely different from comparing the means directly. It is really about variance. This is the key idea, more than 100 years old now.

Lecturer L2 41:47

The derivation has five steps.

  1. Split a deviation by adding and subtracting
  2. Replace unknown means with their estimators:
  3. Square both sides and sum over all observations, using
  4. The mixed term disappears:
  5. What remains is the theorem.
Theorem: partitioning the sum of squares
NameMeasuresMeaning
total sum of squares celkový součet čtvercůobservations around the overall meanall the variability. It is the sample variance without dividing by
between-groups sum of squares regresnígroup means around the overall meanvariability explained by factor
within-groups (residual) sum of squares reziduálníobservations around their own group meanvariability that remains unexplained

If you have a data set, it has a fixed total sum of squares. Once you have the data, this number is fixed. But it is a question how to write one fixed number by a sum of two non-negative numbers. For example, 10 can be 5 plus 5, but also 1 plus 9. This is the essential idea of ANOVA.

Lecturer L2 53:04
Example

The whole of ANOVA by hand, on nine numbers

Three groups of three: A = (1, 2, 3), B = (3, 4, 5), C = (8, 9, 10). The group means are 2, 4 and 9, and the grand mean is 5.

group A, mean 2group B, mean 4group C, mean 9
0246810ABCgroupvaluegrand mean 5
Thick lines are the group means. Dashed lines are the distances inside each group, which go into SSe. The distances from the group means to the grand mean go into SSA.
SumCalculationResultdfSS / df
betweeneach person counts their group's distance: 78239
withininside each group: 661
totalall nine around 5: 848

The degrees of freedom are and Check: and ✓ Then The critical value is so reject , and R agrees:

R
v <- c(1, 2, 3, 3, 4, 5, 8, 9, 10)
g <- factor(rep(c("A", "B", "C"), each = 3))
summary(aov(v ~ g))
            Df Sum Sq Mean Sq F value  Pr(>F)
g            2     78      39      39 0.00036
Residuals    6      6       1
Watch out

The names are easy to swap, and it happened once in the lecture too. Remember: A is between groups, e is within groups.

Check yourself and What is

So the groups explain 30 % of the variability.

2.5Degrees of freedom and distributions

In plain words

Rule for degrees of freedom: count the values, then subtract 1 for each average you had to estimate.

SumValues usedConstraintsdfDistribution
Total, under values 1:
Between, under values 1:
Residual, always values one per group

Check: The degrees of freedom add up just like the sums of squares.

It is not a mystery to work with the degrees of freedom. We are starting with the question how many observations you are using. But for each condition which is involved, you must take minus one in the degrees of freedom.

Lecturer L2 61:44

Why chi-squared? Each observation is normal. Averages and differences of normal variables are normal. After standardizing (dividing by because everything is squared) you have a sum of squared standard normals. That is the definition of

2.6The omnibus F-test

Theorem: omnibus ANOVA F-test

Under If we reject at level

In plain words

asks: is the spread between the groups large compared with the normal noise inside the groups? Mean squares ( are sums of squares divided by their degrees of freedom, so they are fair to compare.

The famous result of ANOVA, the original idea by Fisher, is this trick. Use two sums of squares, which both incorporate the sigma square, and make a ratio of them. This is a clear mathematical way how to cancel the unknown sigma square.

Lecturer L2 67:50

Questions about the F-test, answered

  • One-sided or two-sided? One-sided. cannot be negative. Values near 0 mean that group means are close together, which agrees with Only large values speak against
  • Why these distributions? is defined as the ratio of two independent (chi-squared / its df). Here both are divided by which cancels.
  • under For the mean is so For the diets, So under expect values near 1.
  • Limiting values? The smallest possible is when all group means are equal. Under values stay near 1. Under between-group variability is large, and grows without limit as the sample grows.
Check yourselfWhat does F close to 0 tell you about the group means?

is near 0, so every squared difference is near 0. All group means are almost the same as the grand mean. So you do not reject

2.7The ANOVA table

Software always shows the result in this form. Most programs leave out the Total row, because it only serves as a check.

sourcedfsum of squaresmean squaresstatisticp
factor
Residuals
Total
R
anova_model <- aov(WeightLoss ~ Diet, data = dat)
summary(anova_model) |> print(signif.stars = FALSE)
            Df Sum Sq Mean Sq F value  Pr(>F)
Diet         2   71.1   35.55   6.197 0.00323
Residuals   75  430.2    5.74
Example

Read the diet table

  • so groups. so people. A table tells you the size of the study.
  • and
  • reject At least two diets have different mean weight loss.
  • By the critical value: qf(0.95, 2, 75) gives and Same decision.
00.20.40.60.81012345678value of the F statisticdensityF₀.₉₅(2, 75) = 3.12F_A = 6.197rejectdo not reject
The F(2, 75) density. It starts high near 0, and only the right tail is the rejection region.

Remember that in statistics, the response, the variable which is analyzed, is always on the left-hand side. And the model you are using is described by the right-hand side.

Lecturer L2 73:53

You can really see how far you are from non-rejecting. If this red value were very close to the quantile, you can say: okay, we have enough evidence to reject the null hypothesis, but the evidence is really very small.

Lecturer L2 80:35

In statistics, rejection means that in our data set there is enough evidence of something. But not rejecting means it's not the result. We are not able to decide. Maybe there is no change, or maybe we have not much data.

Lecturer L2 81:26
Check yourselfAn ANOVA table has df 3 and 36. How many groups and observations are there?

so groups. so observations.

2.8Two simulated datasets

Both datasets have 3 groups of 15 and the same total, Only the split differs.

Dataset 1: one group is clearly different. Dataset 2: all means nearly equal, but wide spread.
SSA: explained by the groupsSSe: unexplained, inside the groups
0100200300393sum of squares (the total is always 393)Dataset 1: SSA = 353.8, SSe = 39.2Dataset 2: SSA = 0.7, SSe = 392.3
The same total variability. Dataset 1 is mostly explained by groups, and dataset 2 is mostly noise.
dfSum SqMean SqFp
Dataset 1: A2353.8176.91189.6<2e-16
Dataset 1: Residuals4239.20.93
Dataset 2: A20.70.350.0370.963
Dataset 2: Residuals42392.39.34
00.20.40.60.81012345value of the F statisticdensity3.22Dataset 2: F = 0.037Dataset 1: F = 189.6 is far off the chart →
Critical value qf(0.95, 2, 42) = 3.22. Dataset 2 is well below it, and dataset 1 is far above.

This leads to a conclusion that almost all the variability is inside the residuals. It means that the model was not able to explain. So the grouping cannot help us, and you are not rejecting the null hypothesis.

Lecturer L2 84:36

2.9Estimators in ANOVA

  • is an unbiased estimator of the grand mean
  • are unbiased estimators of the group means
  • are unbiased estimators of the effects
  • so is an unbiased estimator of the error variance
Confidence interval for a group mean

This is the usual recipe, estimate ± critical value × standard error, with one improvement. ANOVA assumes the same in all groups, so we estimate it with using all the data and not only one group. That is why the degrees of freedom are and not More degrees of freedom give a smaller critical value and a narrower interval.

Example

95 % CI for diet A

so which gives kg.

Dietmeanmargin95 % CI (kg)
A243.3000.974(2.33; 4.27)
B273.0260.918(2.11; 3.94)
C275.1480.918(4.23; 6.07)

This is something for confidence intervals for each group means. We can estimate the mu, but we can also make a confidence interval. And you know this. This is the formula from the two-sample t-test. Nothing new.

Lecturer L2 87:35
Watch out

The intervals of A and C overlap a little, yet these two diets do differ significantly. Compare groups using the interval of the difference. See the overlap trap.

2.10ANOVA as a comparison of two models

  • One-way ANOVA model:
  • Null model:

is a submodel of you get it when all So ANOVA tests is valid, against is valid.

In statistics, this is very nice that many things can be formulated as comparing two statistical models: some complicated model and some very simple so-called null model. It has only one limitation: the small model must be a so-called submodel of the big model.

Lecturer L2 92:08

You will see this again in Lecture 6, where anova(m1, m2) compares regression models.

2.11Post-hoc tests

  • not rejected: not enough evidence against equal means. Stop.
  • rejected: continue. Which pairs or sets differ? You still need to control the familywise error rate.
Watch out

Post-hoc tests are valid only after the omnibus test has rejected

If you do not reject the null hypothesis in the omnibus test and you start using the post hoc tests, the results are not correct.

Lecturer L2 94:20
MethodIdeaWhen to use
Bonferroni (1936, Miller 1966)Use For all pairs, Only with few groups (suggested Otherwise very conservative, with very low power.
Tukey's HSD (1949)Pairwise CIs using the studentized range instead of t quantiles.The gold standard for pairwise comparisons. More powerful than Bonferroni.
Scheffé (1959)Uses quantiles of the F distribution. Can compare pairs and also sets of groups.Complicated hypotheses (linear contrasts). Very conservative.
Tukey's simultaneous CI for μᵢ − μₗ
In plain words

"Simultaneous" means that the 95 % covers all the intervals together: in 95 % of samples, every pair's interval catches its true difference. Ordinary 95 % intervals would each have their own 5 % risk, and those risks add up. So Tukey uses a larger critical value, which comes from the distribution of the largest difference among means (the studentized range, in R qtukey).

Example

Tukey's interval for diets A and C, by hand

qtukey(0.95, 3, 75) gives so the critical value is The ordinary one was which shows the price of testing all pairs. The standard error is

0 is outside, so A and C differ, which agrees with the Tukey p-value of 0.0201 below.

A linear contrast kontrast is with Examples for

  • Compare and
  • Compare and

This is the gold standard. If you want to learn one method to begin with, Tukey's method.

Lecturer L2 95:54
Check yourselfThe omnibus test gives Do you continue with Tukey's test?

No. is not rejected, so you stop. Post-hoc tests are valid only after the omnibus test has rejected

2.12Reading post-hoc results

Compact Letter Display (CLD)

Two groups that share a letter are not significantly different. Groups with no shared letter are different. The original CLD also ranks the groups from the highest mean to the lowest.

R
agricolae::HSD.test(anova_model, "Diet", group = TRUE)$groups |> rownames_to_column("group")
  group WeightLoss groups
1     C   5.148148      a
2     A   3.300000      b
3     B   3.025926      b
# also: agricolae::LSD.test(anova_model, "Diet", p.adj = "bonferroni", group = TRUE)
#       agricolae::scheffe.test(anova_model, "Diet", group = TRUE)

C has letter a, while A and B have letter b. So C differs from A and from B, and A and B do not differ. All three methods agree here.

The letters are drawn on the boxplot.

Table of pairwise comparisons

Use group = FALSE to get the differences, p-values and confidence intervals.

ContrastdifferenceBonferroni pTukey pScheffé pDecision
A − B0.2741.00000.91250.9203no difference
A − C−1.8480.02240.02010.0272different
B − C−2.1220.00510.00480.0070different
BonferroniTukeyScheffé
-4-3-2-1012difference of means (kg)no differenceA − BA − CB − C
Confidence intervals for pairwise differences. If an interval contains 0, that pair does not differ. Tukey is the narrowest, Scheffé the widest.
Check yourselfThree groups have the letters a, ab and b. Which pairs differ significantly?

Only the pair a and b, because they share no letter. Group ab shares a letter with each of them, so it does not differ from either.

2.13Checking the assumptions

  • Independence is controlled by the design of the experiment. It cannot be tested afterwards.
  • Normality:
  • Homogeneity of variance homogenita rozptylu:

Equivalently, In practice:

  1. Fit the ANOVA model.
  2. Calculate residuals rezidua
  3. Check normality of the residuals. If it looks suspicious, also check within each group.
  4. Check homogeneity of variances of the residuals.

Do not forget to go back and check the assumptions. If you do not check the assumptions and just use the results, it can be completely incorrect. You must check, either at the beginning or at the complete end.

Lecturer L2 101:14
NormalityHomogeneity of variance
TestsShapiro-Wilk (shapiro.test): standard, high power, Others: Anderson-Darling ( Lilliefors ( weak power).Levene (car::leveneTest): standard, highly robust to outliers. Bartlett (bartlett.test): needs precise normality, not robust to outliers, but high power.
GraphsQ-Q plotboxplots, residuals vs. fitted values
If violatedThe F-test is highly robust. It really needs normality of the sample means. With it is robust to mild skewness and kurtosis (Central Limit Theorem). With severe skewness and outliers bias the group mean and increase Balanced ( robust up to a variance ratio 1:4, that is standard deviation (or IQR) ratio 1:2. Unbalanced: the F-test can give falsely low p-values (liberal) or falsely high p-values (conservative, low power).
What to doKruskal-Wallis, if normality is severely violated with small samples, or there are many outliers.Data transformations, or Welch's ANOVA (Welch, 1951): oneway.test(..., var.equal = FALSE).

Surprisingly, ANOVA is very robust. Even if your data are relatively far from normality, it can be safely used. The reason is that there is somewhere the central limit theorem in the background: calculating averages makes the probability distribution closer to the normal automatically.

Lecturer L2 102:24

About testing homogeneity of variance: this is a very important assumption. You must check. Levene's test should be something like a gold standard to test the homogeneity of variance.

Lecturer L2 103:09
Example

Assumptions for the diets

R
diag <- broom::augment(anova_model)
shapiro.test(diag$.resid)
W = 0.99208, p-value = 0.9161
diag |> summarise(.by = Diet, Shapiro_p = shapiro.test(.resid)$p.value)
B 0.961   A 0.0775   C 0.372
car::leveneTest(WeightLoss ~ Diet, data = diag)
Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  2  0.6257 0.5377
      75

All p-values are above 0.05. We do not reject normality or equal variances, so the ANOVA result can be used.

Diagnostic plots: Q-Q plot of all residuals, Q-Q plots by group, boxplots of residuals, and residuals against group means.

Summary list from the lecture. You should be able to explain: the basic idea and typical examples of ANOVA; assumptions (data types, normality, homogeneity); the model equation in its different parameterizations, with interpretation; the hypothesis in equivalent forms; sums of squares, omnibus F-test and statistic; reading the ANOVA table; effects, group means and grand mean; post-hoc tests; methods of multiple comparison, tables and visualizations.

Check yourselfWhich of the three ANOVA assumptions cannot be tested after you have the data?

Independence. It depends on the design of the experiment. Normality can be checked with Shapiro-Wilk and a Q-Q plot, and homogeneity with Levene's test.

2.14Two-way ANOVA: two factors at once

Watch out

The lecturer said that the syllabus is about one-way ANOVA, and that two-way is an additional part, "something more than expected". Learn one-way first, and use the rest for the seminars and for practice. It is covered here for completeness.

You should really relatively deeply understand the one-way ANOVA. Continue reading about the two-way ANOVA: the same idea, but you have two factors. We can at least look at the practical usage of the two-way ANOVA.

Lecturer L2 104:07

Example: tooth growth of 60 guinea pigs (Crampton, 1947). len = length of odontoblasts in micrometers. dose = vitamin C, 0.5, 1 or 2 mg per day. supp = delivery method: OJ (orange juice) or VC (ascorbic acid).

suppdosesizemeanst.devlowestQ1medianQ3highest
OJ0.51013.24.468.29.712.216.221.5
OJ11022.73.9114.520.323.525.627.3
OJ21026.12.6622.424.626.027.130.9
VC0.5107.982.754.25.957.1510.911.5
VC11016.82.5213.615.316.517.322.5
VC21026.14.8018.523.426.028.833.9
Boxplots for each combination, and for each factor alone.
Two-way ANOVA model

Two-way ANOVA dvoufaktorová analýza rozptylu / dvojné třídění:

Factor has levels and factor has levels.

  • the -th observation in level of and level of
  • grand mean. cell mean.
  • main effect hlavní efekt of level of regardless of main effect of level of regardless of
  • interaction effect interakce of level of with level of

Assumptions are the same three as before, with the same in all groups. Identification constraints:

In plain words

Interaction means that the effect of one factor depends on the other factor. In a medical comparison: drug A may be better for young people and drug B for older people. In a plot of means, parallel lines mean no interaction.

No interaction: parallel lines
0102030lowmidhighmean
Interaction: the gap changes
0102030lowmidhighmean
Made-up illustration of the two situations.

Sums of squares, balanced design

Fisher (1925) derived the model for the balanced design, where every cell has the same size

SumFormula follows
Theorem (balanced design)

Each row of the table has its own which follows an F distribution under its own null hypothesis.

R
anova_model <- aov(len ~ supp + dose + supp:dose, data = dat)   # or
anova_model <- aov(len ~ supp * dose, data = dat)
summary(anova_model) |> print(signif.stars = FALSE)
            Df Sum Sq Mean Sq F value   Pr(>F)
supp         1  205.4   205.4  15.572 0.000231
dose         2 2426.4  1213.2  92.000  < 2e-16
supp:dose    2  108.3    54.2   4.107 0.021860
Residuals   54  712.1    13.2

df check:

The order of testing matters

  1. Test the interaction first: all against some Look at and
  2. If rejected: the impact of varies across the levels of Evaluating main effects can be misleading. Examine simple main effects.
  3. If not rejected: test and interpret main effects. that is all that is all
OJ: orange juiceVC: ascorbic acid
01020300.512dose of vitamin C (mg per day)mean tooth lengthlines meetOJ is higher
Mean tooth length. OJ is better at low doses, but at dose 2 they are equal. That is the interaction, with p = 0.022.
Example

Means, effects and coefficients

Means (grand mean 18.81)dose 0.5dose 1dose 2supp mean
OJ13.2322.7026.0620.663
VC7.9816.7726.1416.963
dose mean10.60519.73526.100
  • Main effects: OJ VC dose
  • Interaction effects: OJ VC They sum to zero in each row and column.
  • Check for OJ at dose 0.5: ✓

Software shows reference-group coefficients: (Intercept) 13.23, suppVC −5.25, dose1 9.47, dose2 12.83, suppVC:dose1 −0.68, suppVC:dose2 5.33.

The reference cell is OJ at dose 0.5. For VC at dose 2: ✓

Multiple comparison

Tukey's method can be applied to the combinations or to each factor.

CombinationmeanTukeyScheffé
VC:226.14aa
OJ:226.06aa
OJ:122.70aa
VC:116.77bb
OJ:0.513.23bbc
VC:0.57.98cc

Tukey by factor: OJ a, VC b. Dose 2 a, dose 1 b, dose 0.5 c. Scheffé is more conservative: OJ:0.5 gets "bc", so it is not separated from VC:0.5.

R
agricolae::HSD.test(anova_model, c("supp", "dose"), group = TRUE)$groups
agricolae::HSD.test(anova_model, "supp", group = TRUE)$groups
agricolae::HSD.test(anova_model, "dose", group = TRUE)$groups
agricolae::scheffe.test(anova_model, c("supp", "dose"), group = TRUE)$groups
Letters on the boxplots, for Tukey's method.
Confidence intervals for all 15 pairs, by three methods.

The full Tukey table of 15 pairs is on. Pairs that are not different at 5 %: OJ:0.5 vs VC:1 ( OJ:1 vs OJ:2 ( OJ:1 vs VC:2 ( OJ:2 vs VC:2 ( The other 11 pairs are significantly different.

Check assumptions

R
diag <- broom::augment(anova_model)
shapiro.test(diag$.resid)
W = 0.98499, p-value = 0.6694
diag |> summarise(.by = c("supp","dose"), Shapiro_p = shapiro.test(.resid)$p.value)
VC:0.5 0.170   VC:1 0.270   VC:2 0.919   OJ:0.5 0.182   OJ:1 0.415   OJ:2 0.815
car::leveneTest(len ~ supp * dose, data = diag)
      Df F value Pr(>F)
group  5  1.7086 0.1484
      54

All p-values are above 0.05, so normality and homogeneity are not rejected.

The diagnostic plots for the two-way model.

Unbalanced two-way ANOVA

When cell sizes are unequal, the design loses orthogonality: main effects and interaction become correlated, and their sums of squares overlap. They no longer sum to So the order of testing starts to matter.

TypeCompares modelsNote
I, sequential Y~A; then Y~A Y~A+B; then Y~A+B Y~A+B+A:BDepends on the order of the factors. is unadjusted for
II, hierarchicalY~A Y~A+B and Y~B Y~A+B; then Y~A+B Y~A+B+A:BIndependent of the order
III, partialY~A+A:B Y~A+B+A:B and Y~B+A:B Y~A+B+A:B; then Y~A+B Y~A+B+A:BIndependent of the order

Testing: first the interaction.

Interaction significantInteraction not significant
Type IDo not interpret main effects, examine simple effects. is adjusted for but is unadjusted for
Type IIDo not trust main effect tests. The statistics are biased because they assume no interaction.Directly read Independent of order.
Type III and use unweighted marginal means and test the main effects while holding the interaction effect.Directly read Independent of order.
R
car::Anova(lm(len ~ supp * dose, data = dat), type = 2) |> print(signif.stars = FALSE)
           Sum Sq Df F value    Pr(>F)
supp       205.35  1  15.572 0.0002312
dose      2426.43  2  92.000 < 2.2e-16
supp:dose  108.32  2   4.107 0.0218603
Residuals  712.11 54
car::Anova(lm(len ~ supp * dose, data = dat,
              contrasts = list(supp = contr.sum, dose = contr.sum)), type = 3)
             Sum Sq Df  F value    Pr(>F)
(Intercept) 21236.5  1 1610.393 < 2.2e-16
supp          205.4  1   15.572 0.0002312
dose         2426.4  2   92.000 < 2.2e-16
supp:dose     108.3  2    4.107 0.0218603
Residuals     712.1 54

These data are balanced, so Types I, II and III all give the same numbers.

Check yourselfThe interaction is significant. Should you interpret the main effects directly?

No, this can be misleading, because the effect of one factor depends on the other. Examine the simple main effects.

Lecture 3 · 29 September 2026

Ranks, rank-based tests, permutation tests

What can you do when the data are not normal, or there are outliers, or the data are only ordinal? Use the order of the values instead of the values.

In plain words

You will need: the median and outliers, the binomial distribution, the central limit theorem and the coin test. The sign test below is that coin test.

3.1Parametric or nonparametric?

Parametric methodsNonparametric methods
AssumptionA strict family of distributions, for example No parametric assumption. Only general ones, for example "continuous" or "symmetric".
Work withPoint and interval estimates and tests of the parametersRanks or rearrangements of the sample
DataOnly data that fit the assumptionA wider class of data
  • Rank-based tests pořadové testy: nonparametric tests based on the ranks of the variables in a random sample.
  • Permutation tests permutační testy: nonparametric tests where the distribution of the statistic comes from calculating all possible values after rearranging the sample.

Once some theory assumes that your data are coming, for example, from the normal probability distribution, you are no longer required to speak about the normality. You can simply work with the mu, you can estimate the mean mu, you can test the mean mu. This is the reason why we are speaking about parametric methods.

Lecturer L3 3:11

From the point of view of the theory in the background, the nonparametric methods are much more difficult to be developed. But on the other hand, the practical usage is much easier. Our target is the practice and to understand the algorithm.

Lecturer L3 17:45

3.2Ordered sample and order statistics

Let be a random sample of at least ordinal type. Sort it to get the ordered sample uspořádaný výběr:

  • is the -th order statistic pořádková statistika. is the sample minimum, the sample maximum.
  • Ties shodné hodnoty are observations with the same value.

From a continuous distribution: no ties, for so The density of is:

Watch out

Order statistics are neither independent nor identically distributed. You only sorted the numbers, but you lost both properties of a random sample.

order 1 (minimum)order 2order 8 (median)order 14order 15 (maximum)original N(0,1)
00.40.81.2-4-3-2-101234xdensity
Sample of n = 15 from N(0, 1). Each order statistic has its own distribution. Computed with the formula above.

This is maybe slightly surprising that you are having the same data. The only difference is that you sort the data. But after ordering, you are losing everything from the assumptions of the random sample. The ordered values are no more independent, and they have different probability distributions.

Lecturer L3 14:42

3.3Ranks

The rank pořadí of is its position in the ordered sample. When there are no ties:

  • Each permutation has the same probability
  • The distribution of ranks does not depend on the distribution of the original sample.
  • and
  • The sum of ranks is fixed:

So rank-based tests are distribution-free.

It does not mean that there is no probability distribution behind the ranks. There are some special probability distributions. But distribution-free means that there is no connection to the probability distribution of your original data. This is the reason why the rank-based tests are so popular.

Lecturer L3 26:34

Ties

Real data are rounded, so ties happen even if the theory says they should not. Then you must adjust the ranks.

MethodFormulaIdea
Average ranks (mid-ranks)Give all tied values the average of their positions
Standard competitionAll tied values get the best position. Two golds, then bronze.
Modified competitionAll tied values get the worst position
Dense rankingRanks only for unique values, with no gaps
Random rankingTies are broken at random
Rule

Average ranks are the only ranks that keep their fixed sum. So rank-based tests use average ranks.

Yes, the random ranks will keep this, but if you give the data to people who are doing the same, they will obtain a different result. So it is not used in statistics, because you are not able to come to a unique result.

Lecturer L3 32:30
R
order(X)                              # ordering permutation
sort(X)                               # ordered sample, same as X[order(X)]
rank(X)                               # ranks
rank(X, ties.method = "average")
Example

All ranking methods on one sample

is at positions 4 and 5, so the average rank is 4.5. is at positions 6, 7, 8, so the average rank is 7.

Check yourselfFind the average ranks of the values 3, 5, 5, 9. Does the sum fit the formula?

The ranks are 1, 2.5, 2.5, 4. The sum is 10, and ✓

3.4Running example: guessing one minute

Ten participants, independently and without training, had to guess when one minute had passed after a sound signal.

Test at 5 % that half of the participants underestimated and half overestimated: against

This is really a well known result, that we rather think about not exceeding the deadline. Eight of the people pressed the button after a time less than 60 seconds. Only two people pressed the button after the 60 second period.

Lecturer L3 39:29

3.5Sign test

The sign test znaménkový test: let be a random sample from a continuous distribution with median so Test against

  1. Calculate the differences
  2. Count the positive ones:
In plain words

Forget the values and keep only "above or below". If the median really is each value is above it with probability ½, like a coin flip. So is the number of heads in flips.

Sign test

Exact (small samples). Under with and

Reject at level if or Here is the largest number with and also

Asymptotic (large samples). By the de Moivre-Laplace theorem, one of the central limit theorems centrální limitní věta: If reject at asymptotic level

Example

Sign test on the one-minute data

53484555635166565058
−7−12−15−5+3−9+6−4−10−2

and Since is not rejected.

R
S_plus <- sum(dat$X > 60)
n <- nrow(dat)
binom.test(S_plus, n, p = 0.5, conf.level = 0.95)
number of successes = 2, number of trials = 10, p-value = 0.1094
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
 0.02521073 0.55609546
sample estimates: probability of success 0.2

Where the p-value comes from. If is true, so count the outcomes at least as extreme as 2:

What the interval says. The 95 % CI is for the probability of guessing above 60 seconds. It contains 0.5, the value under so this also says "do not reject". It is an exact binomial interval, and it is not symmetric around 0.2. It is very wide, because 10 people give little information. See intervals for a proportion.

Is that surprising? 8 of 10 people were below 60, yet the test does not reject. This is the low power of the sign test.

The sign test has very low power, really very low power. If you use a sample size of ten, the test is not able to decide simply because it has very low power.

Lecturer L3 53:46

The sign test throws away the sizes of the values and keeps only their direction. Compare three tests on the same ten numbers:

Test of "centre = 60"Usesp-valueDecision at 5 %
Sign testonly above or below0.1094do not reject
Wilcoxon signed-rankdirection and rank of the size0.0371reject
One-sample t-testthe values themselves, and assumes normality0.0263reject
In plain words

More information usually means more power. But you may not pick the test with the p-value you like. Choose the test before you see the result, based on what you can assume about the data.

00.050.10.150.20.25012345678910S⁺, the number of positive differencesprobabilityqbinom(0.025) = 2 = S⁺ observedqbinom(0.975) = 8
Bin(10, ½): dbinom(x, size = 10, prob = 0.5) and qbinom(c(0.025, 0.975), size = 10, prob = 0.5). S⁺ = 2 lies on the border, still inside the region of non-rejection.

For a larger sample, the binomial looks more and more normal. This is why works:

00.050.10.150510152025S⁺ for n = 25probabilitynormal curve N(12.5, 2.5²)
Bin(25, ½) with the normal curve from de Moivre-Laplace.

Notes on the sign test

  • It is used especially for skewed distributions, which are surely not Gaussian. The t-test would give incorrect p-values there.
  • It has relatively low power, so a large sample is necessary.
  • Zeros: differences are typically removed, and the statistic is calculated on the reduced sample.
  • The asymptotic variant is fairly good when

If some difference is equal to zero, there's no way how to decide whether the difference is positive or negative. You simply behave as if there is no such observation. You are working with a so-called reduced sample.

Lecturer L3 58:49
Check yourselfWith and 3 values above what are its expected value under and

and Since is not rejected. With the exact binomial version is better.

3.6Paired tests

Often you have i.i.d. pairs of dependent observations usually "before" and "after" a treatment.

Hypotheses are about the difference of the same parameter in and For the paired sign test: against

The recipe

Calculate then run the one-sample test on

Watch out

A paired test is not a two-sample test. Paired: the same object twice, values depend on each other. Two-sample: two independent groups. The weight before and after a diet is paired, which is why WeightLoss was calculated in Lecture 1.

3.7Wilcoxon signed-rank test

A rank test for the location of a sample, or for comparing two paired samples, of at least ordinal type. Wilcoxon (1945), popularized by Siegel (1965).

Let come from a distribution symmetric around the point .

If...Then the hypothesis is
General form symmetric around symmetric around
(for example continuous), and the median is unique is the median.
the mean is defined is also the mean.
the point of symmetry is known symmetric around not symmetric around

The algorithm

  1. Calculate the differences
  2. Sort them by absolute value:
  3. is the rank of in this sequence.
  4. Calculate or the rank sums and
Watch out

Rank the absolute values, and give the sign back afterwards. The lecturer says that students often forget this.

Theorem

If where is the critical value of the Wilcoxon test, reject at level

Asymptotic: If reject at asymptotic level

Properties:

  • has a special discrete distribution:
00.0250.050.0750.1051015T⁺ for n = 5probability
Distribution of T⁺ for n = 5, computed exactly. It is symmetric, with an unusual shape.
Example

Wilcoxon on the one-minute data

153−76−1
248−129−1
345−1510−1
455−54−1
563+32+1
651−97−1
766+65+1
856−43−1
950−108−1
1058−21−1
  • and So
  • and
  • Since we reject .
R
wilcox.test(dat$X, mu = 60, alternative = "two.sided")
        Wilcoxon signed rank exact test
V = 7, p-value = 0.03711
alternative hypothesis: true location is not equal to 60

R reports as V. Its p-value is below 0.05, so we reject too. The sign test on the same data could not reject.

00.010.020.030.040510152025303540455055T⁺ for n = 10probabilityquantiles 9 and 46T⁺ = 7
dsignrank(x, n = 10) and qsignrank(c(0.025, 0.975), n = 10). T⁺ = 7 lies outside the non-rejection region.

Notes on the Wilcoxon signed-rank test

  • The one-sample t-test is its parametric analogy.
  • Asymmetric data: can be rejected even if holds. Use the sign test in that case.
  • Zeros: originally not addressed. Later the reduced sample was recommended: remove zeros. Pratt (1959) proposed the signed-rank zero procedure: include zeros for ranking but exclude them from (taking
  • Ties: use average ranks, which lead to a different distribution of the statistic and different p-values, or random tie-breaking.
  • The asymptotic variant is fairly good when Mean and standard deviation are adjusted when there are zeros or ties.

Typically people check the data, the data are far from normal: let us use the Wilcoxon signed rank test instead of the one-sample t-test. But people forget about checking visually the symmetry. If your data are really very asymmetric, you should not use this test.

Lecturer L3 76:28

Sign test against signed-rank test

below 60: minus signabove 60: plus sign
4550556065time (seconds). The number on each point is the rank of its distance from 60tested median69104275381
The sign test sees only the color of each point. The signed-rank test also uses the number.

The Wilcoxon test uses much more information from the data than the sign test. Therefore you should expect that the Wilcoxon test has always higher power than the sign test, because in fact the sign test uses only the color, but not the ranks.

Lecturer L3 78:19
Check yourselfWhy do we rank the absolute differences and not the differences themselves?

The rank should measure how far a value is from in either direction. The direction is kept separately in the sign. Then and can be compared.

3.8Mann-Whitney / Wilcoxon rank-sum test

This compares two independent samples of at least ordinal data. It is the nonparametric analogy of the two-sample t-test. In Czech: dvouvýběrový Wilcoxonův test. Wilcoxon (1945), Mann and Whitney (1947).

Data: from and from

VersionNote
Mann-Whitney, for numeric data or the original, stochastic order
Generalidentical: different: consistent only when
Strict, for numeric dataidentical: shifted by tests for a difference in medians

You should always state the null and alternative hypothesis, because this is a nice example where the formulation of the conclusion depends on the version you used. If you started with this, your conclusion is they have different probability distributions. If you started to test this, your conclusion is they have different medians.

Lecturer L3 89:47

The algorithm

  1. Join both samples:
  2. Sort the combined sample:
  3. are the ranks of the values, and the ranks of the values, in the combined sample.
  4. Calculate the rank sums and
  5. Calculate and
Theorem (Mann-Whitney-Wilcoxon)

Test statistic:

If reject at level

Asymptotic: with and If reject at asymptotic level

Other facts:

  • over all pairwise comparisons. So counts how often an beats a
  • With ties, an adjusted formula for is used.
  • Rank-sum statistics have a special discrete distribution. See dwilcox(x, m, n).
Example

Does the fertilizer affect wheat yield?

Two methods were tested on 13 fields of the same soil quality: method A on 8 fields, method B on 5 fields. Yields in tons per hectare:

With so few points and an unusual low value, normality is doubtful, so a rank test is a good choice.
(sorted)4.24.34.44.55.05.15.25.45.55.65.75.85.9
rank12345678910111213
groupBABBBAABAAAAA
  • with with
  • Check: ✓
  • Since is rejected.
R
wilcox.test(Yield ~ Fertilizer, data = dat, alternative = "two.sided")
        Wilcoxon rank sum exact test
W = 34, p-value = 0.04507
alternative hypothesis: true location shift is not equal to 0

R reports as W.

The t-test sees the yields
44.555.56AByield (t/ha)
The rank test sees only the positions
135791113ABrank
The same data seen in two ways. Using ranks loses the distances between values.

When working with ranks, the distance between subsequent ranks is always one. So you are losing the information about distance from your original data. But the benefit is that you do not need the normality. It is a typical situation in statistics: you must lose something to gain another method without limitation.

Lecturer L3 92:03

Notes

  • Names: Mann-Whitney U test = Mann-Whitney-Wilcoxon test = Wilcoxon rank-sum test.
  • Ties: use average ranks.
  • It is preferable to the t-test when the data are ordinal but not of interval type.
  • It is more robust to outliers.
  • It may have a worse Type I error when the data are both heteroscedastic and non-Gaussian.
  • With different shapes of densities (for example different variances), can be rejected even if holds.
  • The asymptotic variant is fairly good when The standard deviation is adjusted when there are zeros or ties.
Check yourselfWhy are rank tests safe with outliers? Imagine that the lowest wheat value was 0.2 and not 4.2.

Its rank stays 1. Ranks do not see distances, so the extreme value cannot pull the result. The t-test would be heavily affected, because the mean and variance use the actual value.

Check yourselfWith and find and

Since we get So

3.9Kruskal-Wallis test

The nonparametric analogy of one-way ANOVA and the extension of the Mann-Whitney test to more samples. Kruskal and Wallis (1952).

  • Data: a variable of at least ordinal type, and a categorical grouping variable
  • The observations in group are a random sample from a distribution with CDF All samples are mutually independent.
  • for all
  • there exist with or for all So at least one sample stochastically dominates another.
  • implies that the mean ranks of all groups are the same.
  • The homogeneity of variances is still required, as it is included in

The algorithm

  1. Join all observations.
  2. Sort them: with
  3. is the (mid)rank of in the combined sample.
  4. Calculate the sum of ranks in each group:
Theorem (Kruskal-Wallis test)

If the critical value of the test, reject at level

Under and If reject at asymptotic level

  • Adjustment for ties (suggested when more than 25 % of the data are tied): with where is the size of each tied group.
  • The asymptotic quantiles can be quite different from when any
  • If is rejected, continue with post-hoc tests, for example pairwise Mann-Whitney-Wilcoxon tests with a Bonferroni correction.

It is basically the same [as the table in one-way ANOVA]. The only change is that instead of using the observations, you are using the ranks. So at first you translate the values into ranks, and for each category you use the sample size and the sum of the ranks.

Lecturer L3 97:14
Example

Potato varieties

The total weight of potatoes from one plant was measured for four varieties. Compare the location shift across varieties.

Varietyweights ranks
10.9, 0.8, 0.6, 0.93.5, 2, 1, 3.5410
21.3, 1.0, 1.311, 5.5, 11327.5
31.3, 1.5, 1.6, 1.1, 1.511, 13.5, 15, 7.5, 13.5560.5
41.1, 1.2, 1.07.5, 9, 5.5322

With

Ties: values 0.9, 1.0, 1.1 and 1.5 appear twice, and 1.3 three times. So and This gives

and is rejected.

Weights and their ranks per variety.
00.050.10.150.20.2502468101214Qdensityχ²₀.₉₅(3) = 7.815Q_adj = 10.676
The asymptotic decision.
R
with(dat, print(agricolae::kruskal(Weight, Variety)))
$statistics
     Chisq Df    p.chisq
  10.67585  3 0.01361427
$groups
     Weight groups
3 12.100000      a
2  9.166667     ab
4  7.333333      b
1  2.500000      c

The "Weight" column here holds mean ranks: and so on. Variety 3 differs from 4 and 1, and variety 1 differs from all the others. Varieties 2 and 3 share a letter, as do 2 and 4.

Check yourselfYou compare 5 groups with Kruskal-Wallis. What are the degrees of freedom, and what do you do after rejecting

degrees of freedom. After rejecting, use post-hoc tests, for example pairwise Mann-Whitney-Wilcoxon tests with a Bonferroni correction.

3.10Median test

Also called Mood's median test or the Brown-Mood median test.

is the number of observations in group that are greater than the median of the combined sample: If the total sample size is odd, then the of the group that contains the median is increased by

Theorem (median test)

Under If reject at asymptotic level

R
with(dat, print(agricolae::Median.test(Weight, Variety)))
Chi Square = 6.428571   DF = 3   P.Value 0.09252244
Median = 1.1
  Weight groups
3   1.50      a
2   1.30     ab
4   1.10      b
1   0.85      c

the median test does not reject, while Kruskal-Wallis does. It uses only "above or below", so it loses information, just like the sign test. The lecturer noted that it is sometimes preferred when there are many outliers.

3.11Van der Waerden test

It tests the same hypothesis as Kruskal-Wallis, but converts the ranks to quantiles of

and

Theorem (Van der Waerden test)

Under If reject at asymptotic level

R
with(dat, print(agricolae::waerden.test(Weight, Variety)))
$statistics
    Chisq Df    p.chisq
  10.5131  3 0.01467232
$groups (normal scores)
3  0.7945346  a
2  0.1929359  ab
4 -0.1077709  b
1 -1.0599245  c
Test on the potato datastatisticp-valueDecision at 5 %
Kruskal-Wallis10.680.0136reject
Van der Waerden10.510.0147reject
Median test6.430.0925do not reject

For you the Kruskal-Wallis test is the must learn. The so-called median test uses the same idea, but a slightly different formula. Or time to time you can see also the so-called van der Waerden test.

Lecturer L3 100:37

3.12Permutation tests

  • A subset of nonparametric tests, with theory from the 1930s by Fisher and Pitman.
  • They use the exact distribution of a statistic, obtained by calculating its values under all possible rearrangements of the sample.
  • Very computationally intensive.
  • They are based on resampling without replacement: only permutations of the original sample are used.
In plain words

If says the group labels do not matter, then any shuffling of the labels was just as likely as the one you observed. So shuffle the labels in all possible ways, and calculate the statistic each time. If your real value looks extreme among them, reject

  1. Choose a statistic that measures the effect.
  2. Create the distribution of under from its values under all rearrangements of the original sample.
  3. Calculate the observed value
  4. A value of in the extremes suggests a significant effect against
  5. Calculate the p-value according to or or
AdvantagesLimitations
  • They exist for any statistic. Its distribution is not required.
  • They can test things that classic approaches cannot.
  • Ideal for small samples.
  • Useful when parameters are hard to estimate (for example the standard deviation of the statistic), or when parametric assumptions are not met.
  • Computationally intensive.
  • Ad-hoc tests.
  • Primarily provide a p-value.
  • They require exchangeability zaměnitelnost of observations in all samples. In particular, homogeneity of variances is needed when testing a difference in location.
Watch out

Do not mix this up. Resampling with replacement is a different procedure: the bootstrap.

We will allow also repeated values. This seems to be a small change, but statistically, this is a completely different method, with completely different conclusions and features, called bootstrap. You must distinguish these two cases.

Lecturer L3 104:10

A two-sample problem

Independent with CDF and with CDF against

  1. Select a statistic of interest, for example
  2. Calculate the observed value
  3. Let be the combined sample: first values from last from
  4. Let
  5. There are ways to split elements into subsets of sizes and
  6. Under each has probability
  7. Find all of them and calculate for each.
  8. The one-sided p-value is
Approximated p-value

When there are too many rearrangements, resample without replacement times, with large, usually

Example

My example: a permutation test on the wheat data

This example is mine, not from the lecture. It uses the wheat data with a two-sided alternative. There are possible rearrangements, few enough to compute all of them.

050100150-1-0.500.51T = mean(B) − mean(A) after a rearrangementnumber of rearrangementsT* = −0.69
All 1287 values of T. Red bars are the rearrangements at least as extreme as the observed value.

Of the 1287 rearrangements, 56 are at least as extreme as so and we reject at 5 %. I checked this count in R. The rank test gave which is very similar.

Summary list from the lecture. Parametric and nonparametric methods (assumptions, comparison). Ordered sample and (adjusted) ranks. Tests based on ranks: sign test, Wilcoxon test, M-W-W test, with hypotheses, principles, calculating the ranks and statistics, and decisions. Tests for multiple groups: Kruskal-Wallis, median test, Van der Waerden (model, hypothesis, distribution of the statistic, post-hoc tests, comparison to one-way ANOVA). Permutation test: the general idea.

Check yourselfWhat is the difference between a permutation test and the bootstrap?

A permutation test resamples without replacement, so it only rearranges the original values. The bootstrap resamples with replacement.

Lecture 4 · 6 October 2026

Goodness-of-fit tests

How can you test whether your data follow a given distribution?

In plain words

You will need: expected values and the binomial, the central limit theorem and the chi-squared distribution. The idea is simple: compare the counts you got with the counts the theory expects.

4.1Why we need these tests

Often we need to test whether a random sample comes from a specific distribution or family of distributions:

  • with given parameters, for example
  • with unknown parameters, for example "some Gaussian", "some exponential", Poisson, binomial;
  • with a given probability mass function or density function even your own one.

Where it is used: parametric tests require a specific distribution (the t-test and ANOVA need normality); quality control and compliance with a prescribed distribution; checking random number generators.

Choosing a distribution by its features (Aswath Damodaran, Probabilistic approaches to risk).
Watch out

The lecturer warned about the Seeing Theory page: its CDF uses the other definition, This course uses

Some widely used distributions

DiscreteAbsolutely continuous
Bernoulli (alternative), binomial, multinomial, hypergeometric, Poisson, geometric, negative binomial, discrete uniformGaussian (normal), chi-squared, Student t, Fisher-Snedecor F, lognormal, exponential, gamma, Weibull, beta, continuous uniform

Goodness of fit describes how a distribution (a model) fits the sample. Its measures use the discrepancy between observed values and values expected under the theoretical distribution.

  • Pearson's chi-squared test: do observed frequencies follow the specified distribution?
  • Kolmogorov-Smirnov test: does the observed CDF correspond to the CDF of the specified continuous distribution?
  • Testing normality: the typical distribution of random errors or residuals of many parametric models.

Two examples used below.

Example 1: 84 families with 5 children. Test Bin(5, 0.5).012345
number of families with this many boys3102231144
Example 2: waiting time, 70 clients. Test "exponential".(0,3](3,6](6,9](9,12](12,15](15,18](18,21](21,24]
number of clients14161098535

4.2Observed and expected frequencies

Each of the observations goes into exactly one of disjoint categories (sets, intervals) Let

  • Observed (empirical) frequencies empirické četnosti random variables, the counts from your sample.
  • Expected (theoretical) frequencies teoretické četnosti the counts expected under

the data follow the specified distribution. the data do not follow it.

categorysum
observed frequencies
expected probabilities1
expected frequencies
In plain words

Capital is what happened. Small is what the theory says should happen. The whole test asks: are these two rows close enough?

In goodness of fit test we are actually comparing two quantities. One is from statistics, calculated from your sample. In this case these are the observed frequencies. And one from the theory: the expected frequencies.

Lecturer L4 16:32
Check yourselfYou have 100 observations, and a category has under What is its expected frequency?

4.3Multinomial distribution

The joint distribution of the observed frequencies is the -variate multinomial distribution multinomické rozdělení,

Theorem
  • Each with and
  • are not mutually independent.
  • They are negatively correlated:
In plain words

Binomial sorts things into 2 boxes, and multinomial into boxes. Look at one box only: "in this box, or not?" That is binomial again. The boxes are not independent because the total must be If one box gets more, another must get less, so the correlation is negative.

The sum of these observed frequencies is fixed. Their sum is not random. So there is one constraint. If you know all the values of the capital Ns, except exactly one, you are able to calculate its value. So they are not independent.

Lecturer L4 28:21

4.4Building the test statistic

By the de Moivre-Laplace theorem, for large large and no very large category:

We used because with many categories each must be small. Now square and add, with the binding condition

  • Under for all so
  • Large means some differs a lot from That is evidence against
  • Guess the distribution of under a sum of squares of standard normals, with one binding condition. So it is chi-squared with degrees of freedom.

4.5Pearson's chi-squared test

Theorem: Pearson (1900)

Under is rejected at level if

It is a one-sided test: only large speaks against

Assumptions for the approximation

podmínka dobré aproximace. At least one must hold:

  • (a) Minimum expected counts: for all
  • (b) Yarnold's criterion (1970): where and no

If neither holds: merge appropriate adjacent categories, to increase the expected frequencies.

Yates's correction for continuity (1934), when and are too small (for example only 2 categories, where you cannot merge):

This is not a perfect result. This is an asymptotic result under these limitations. So for the practical usage of this theorem, you really must [check]. Otherwise it can really happen that following this rule will lead you to a completely incorrect result.

Lecturer L4 40:32
Example

First by hand: is this die fair?

Roll a die 60 times. If it is fair, each face has so the expected count is for every face.

Face123456sum
Observed 5898102060
Expected 10101010101060
2.50.40.10.401013.4

So with df. The critical value is and so reject the die does not look fair. Face 6 alone contributes 10 of the 13.4, so the last row also shows you where the problem is. These counts are made up for practice.

R
chisq.test(c(5, 8, 9, 8, 10, 20))
X-squared = 13.4, df = 5, p-value = 0.01991

4.6When parameters are unknown

If is only a family with unknown parameters the modified minimum method estimates them by solving:

Theorem

When parameters estimated this way are substituted into The number of degrees of freedom is reduced by the number of estimated parameters.

Typically in practice it is not used. The typical procedure, not so correct but still working from the point of view of the application, is: use still this formula, but remember that for each parameter you estimate from the same data, you must decrease the degrees of freedom.

Lecturer L4 46:57
Watch out

R's chisq.test does not know that you estimated a parameter, so it reports the wrong degrees of freedom. In that case calculate df and p-value yourself. The lecturer stressed this.

Check yourselfYou have 6 categories and you estimated 1 parameter from the data. How many degrees of freedom does have?

4.7Test for a discrete distribution

  1. Categories are all possible outcomes under
  2. Estimate unknown parameters ( of them), if necessary.
  3. Observed frequencies:
  4. Expected frequencies: using the PMF under
  5. Check the assumptions, and merge suitable adjacent categories if necessary.
  6. Calculate compare with and decide.
Example

Example 1: are the numbers of boys Bin(5, 0.5)?

030.03122.620.054
1100.15613.10.744
2220.31226.20.688
3310.31226.20.860
4140.15613.10.058
540.03122.620.720
sum84184

Always check the sums first: df is not rejected.

nⱼ expectedNⱼ observed
0102030012345number of boysnumber of families
00.050.10.150246810121416K under H₀: χ²(5)densityquantile 11.07K = 3.12
K = 3.12 lies well inside the non-rejection region.
R
chisq.test(tab$N.j, p = tab$p.j)
Warning: Chi-squared approximation may be incorrect
        Chi-squared test for given probabilities
X-squared = 3.1238, df = 5, p-value = 0.6809

R warns because two are below 5. Merge adjacent categories: 0-1 and 4-5.

0-1130.18715.7
2220.31226.2
3310.31226.2
4-5180.18715.7
nⱼ expectedNⱼ observed
01020300−1234−5number of boysnumber of families
00.10.20.30246810K under H₀: χ²(3)densityquantile 7.81K = 2.35
After merging: K = 2.35, df = 3, quantile 7.81, p = 0.503. H₀ is still not rejected, and now the assumptions hold.
R
chisq.test(tab2$N.j, p = tab2$p.j)
X-squared = 2.3492, df = 3, p-value = 0.5032

A note from me: in the first table, Yarnold's criterion (b) already holds, since gives So merging is only required under the stricter rule (a), which is the one R checks.

You should merge logically. You can merge zero boys with five boys mathematically, but at each point of what you are doing with the data, you should be able to logically explain it to anybody. Typically this means: if the rows are somehow sorted, merge only subsequent rows.

Lecturer L4 55:30

4.8Test for a continuous distribution

  1. Categories are disjoint intervals covering all possible outcomes under
  2. Estimate unknown parameters ( of them), if necessary.
  3. Observed frequencies:
  4. Expected frequencies: using the CDF under
  5. Check the assumptions, and merge adjacent categories if necessary.
  6. Calculate compare with and decide.

Suggested number of equidistant intervals, the same as for a histogram: or (Sturges' rule, which is close to optimal for roughly normal data).

Example

Example 2: is the waiting time exponential?

The parameter is unknown, so we estimate it. The maximum-likelihood estimator is Using interval midpoints:

First table: the sum of is 0.932 and the sum of is 65.3, not 70. Something is missing! The theory allows waiting times above 24 minutes. So extend the last interval to

(0;3]1.5140.28620.0
(3;6]4.5160.20414.3
(6;9]7.5100.14610.2
(9;12]10.590.1047.29
(12;15]13.580.07445.21
(15;18]16.550.05313.72
(18;21]19.530.03792.66
(21;∞)∞50.09486.64
sum70170

df because we estimated one parameter. is not rejected. The data do not contradict the exponential distribution.

nⱼ expectedNⱼ observed
05101520(0;3](3;6](6;9](9;12](12;15](15;18](18;21](21;∞)waiting time (minutes)number of customers
00.050.10.15024681012141618K under H₀: χ²(6)densityquantile 12.59K = 4.8

Think about the very different thing, that there is a big hole between data and theory. Data are never equal to plus infinity. In theory almost everything can be plus or minus infinity. In goodness of fit tests you are mixing the theory with the data. So for the practice, really spend a few seconds to do all the checks, all the sums. If you see that the sum of probabilities is less than 1, you must add something.

Lecturer L4 64:05

4.9Empirical CDF

Recall the cumulative distribution function distribuční funkce: It is right-continuous and nondecreasing, from 0 to 1.

Definition

The empirical CDF (ECDF) empirická distribuční funkce of a sample is:

  • It is a right-continuous, nondecreasing step function.
  • Steps are located at the observed values, and each step has height
  • is the indicator of the event: true gives 1, false gives 0.
In plain words

answers: what share of my data is at most Walk from left to right, and at each data point climb one step of

Check yourselfA sample has 10 observations, with no ties. How high is each step of the ECDF?

4.10Kolmogorov-Smirnov test

Kolmogorov (1933). Let the sample come from a continuous distribution with CDF and let be the tested CDF.

against

Theorem: one-sample Kolmogorov-Smirnov test

is rejected at level if is at least the critical value of the test. For large reject if Equivalently,

What is the geometric meaning of It is the largest vertical gap between the two curves.

F̂(x), empirical CDF: a step of 1/n at each observationF₀(x), the tested CDFD: the biggest vertical gap
00.250.50.7510102030405060708090100xcumulative probabilityD = 0.14
Twelve made-up values against Ex(0.04), to show the idea. D is measured vertically, at the place where the curves are farthest apart.

Really saying this very easily, you are comparing two curves. You are looking at the picture, looking at the vertical distances, and you must find the largest gap in the vertical direction. This is exactly the value of the statistic D. If you have a good picture, you can take a ruler and you can really measure the gaps.

Lecturer L4 75:51
Example

Example 3: restart time of a network device

Number of restarts and total restart time of a network device during 246 days. Does the total restart time follow

The empirical CDF with the tested CDF.
Boxplot and histogram with the fitted density.
R
ks.test(dat$time_restart, "pexp", rate = lambda)
Warning: ties should not be present for the one-sample Kolmogorov-Smirnov test
        Asymptotic one-sample Kolmogorov-Smirnov test
D = 0.082674, p-value = 0.06927
alternative hypothesis: two-sided

is not rejected. The biggest vertical gap is about 0.08. By hand, gives the critical value and is below it.

Left: Q-Q plot against Ex(0.04), points close to the line. Right: Q-Q plot against the normal distribution, in a U shape.
In plain words

Reading a Q-Q plot: a U shape opening upward against normal quantiles suggests data on the positive half axis, skewed to the right, such as exponential. In the newer ggplot2 you can make a Q-Q plot against other distributions too.

Check yourselfCan you use this test for binomial data?

No. It needs a continuous distribution. For discrete data use Pearson's chi-squared test.

4.11Two-sample Kolmogorov-Smirnov test

Smirnov (1939). Two independent samples and from continuous distributions with CDFs and

against

Theorem: two-sample Kolmogorov-Smirnov test

is rejected at level if is at least the critical value of the test. For large with reject if

Geometric meaning: the largest vertical gap between two step functions.

You should understand the idea and the geometry in the background. For the evaluation, there is no way to do the Kolmogorov-Smirnov test without numerical software, because the calculation of the p-value is not an easy numerical task.

Lecturer L4 84:35

4.12Assessment of normality

You should remember a few names. The lecturer said not to learn the formulas.

TestBased onIn R
D'Agostino (1970)transformation of skewness, moments::agostino.test
Anscombe-Glynn (1983)transformation of kurtosis, moments::anscombe.test
Jarque-Bera (1980)skewness and kurtosis, moments::jarque.test
Shapiro-Wilk (1965; Royston 1982)order statisticsshapiro.test
Cramér-von Mises (Cramér 1928; von Mises 1928)distance between CDFsnortest::cvm.test
Anderson-Darling (1952)distance between CDFsnortest::ad.test
Lilliefors (1967; Dallal and Wilkinson 1986)like Kolmogorov-Smirnovnortest::lillie.test
Pearson's chi-squared (1900)frequenciesnortest::pearson.test

This is the classical suggestion: if you want to test the normality, for typical cases, start with the Shapiro-Wilk test.

Lecturer L4 86:06

4.13Skewness and kurtosis

For a sample from a continuous distribution:

  • Sample skewness výběrová šikmost measures symmetry about the expected value:
  • Sample kurtosis výběrová špičatost measures tailedness: it is related to the tails, and not much to the peak.
  • Excess kurtosis: It is 0 for the normal distribution, and that is the only reason for the
Theorem

For a sample from a Gaussian distribution, as So a Gaussian sample has and

Example

Three distributions with the same mean

lognormal LN(1, 1.1): positive skewnormal N(5, 4): symmetricWeibull Wb(10, 5.2): negative skew
00.10.20.30.40.502468101214xprobability density
All three have mean 5. Look at the order of mean, median and mode.
distributionskewnesskurtosismeanmedianmode
lognormal LN(1, 1.1)8.34190.4252.720.80
normal N(5, 4)00555
Weibull Wb(10, 5.2)−0.640.5955.115.24
A quick way to read skewness
  • Symmetric: mean ≈ median ≈ mode.
  • Positive skew: mean > median > mode.
  • Negative skew: mean < median < mode.
Simulated data from the same three distributions, with boxplots. The long tail is easy to see for the lognormal.

The mode mód is the most frequent value: the highest bar for discrete data, or the peak of the density for continuous data.

Cullen-Frey plot

fitdistrplus::descdist plots kurtosis against squared skewness for your data, so you can see which distributions are close. Weibull is close to gamma and lognormal.

The dark point is your data, the orange ones bootstrapped values. Normal, uniform, exponential and logistic are single points. Beta is a region, and gamma and lognormal are lines.
Check yourselfA sample has mean 8, median 5 and mode 3. What is the skewness like?

Positive skew, because mean > median > mode. The distribution has a long right tail.

4.14Other normality tests in detail

Watch out

The lecturer said you can skip the details of these tests: "this will not be included in the exam, this is only for those who want to understand how it is possible that some tests will reject normality and other tests will not." But the lecture summary asks for the Lilliefors test in particular, so learn its idea.

Cramér-von Mises and Anderson-Darling

The general idea of both statistics is for against They add up squared gaps instead of taking the largest gap. Both are typically used for normality.

Theorems

Anderson-Darling: reject if

Cramér-von Mises: reject if

Lilliefors test

the sample follows with unknown parameters. non-Gaussian.

  1. Estimate:
  2. Evaluate where is the CDF of

is rejected at level if the critical value of the test. Lilliefors (1967); Dallal and Wilkinson (1986) corrected the critical values.

Check yourselfCompare with the K-S test. What is the difference?

The statistic is calculated in the same way. In K-S, is fully specified in advance. In Lilliefors, and are estimated from the same data, so the curve is already fitted closer to the data, and gaps are smaller. So it needs different, smaller critical values.

Watch out

Do not use the K-S test for normality with estimated parameters.

If you ever see that somebody is using the Kolmogorov-Smirnov test for testing normality, do not do this. This is always incorrect. If you want to test normality you must use the Lilliefors test, because it has different critical values and a different calculation of the p values.

Lecturer L4 98:16

Shapiro-Wilk test

with unknown parameters. non-Gaussian. The statistic is based on order statistics:

The are coefficients corresponding to the order statistics of i.i.d. standard normal variables. Shapiro and Wilk (1965). Royston (1982, 1995) proposed another way of calculating the

Example

Example 3 continued: is the average restart time normal?

Four plots to use for any distribution check: boxplot, Q-Q plot, ECDF with CDF, histogram with density.
Teststatisticp-value
D'Agostino skewnessskew = 1.6741, z = 8.01671.086e-15
Anscombe-Glynn kurtosiskurt = 8.4030, z = 6.08081.196e-09
Jarque-BeraJB = 414.14< 2.2e-16
Shapiro-WilkW = 0.888161.653e-12
Cramér-von MisesW = 0.674699.46e-08
Anderson-DarlingA = 4.38076.651e-11
LillieforsD = 0.113663.601e-08
Pearson chi-squareP = 49.0413.256e-05

All tests agree here: reject normality. In the data, skewness is 1.67 and kurtosis is 8.40, far from the normal values of 0 and 3. (The test reports plain kurtosis, so the reference value is 3.) With data closer to normal, different tests can disagree, because each one looks at a different feature.

4.15Lecture summary and a puzzle

The summary list: empirical and theoretical frequencies and their calculation; Pearson's chi-squared test, statistic, distribution, and degrees of freedom; empirical CDF, Kolmogorov-Smirnov test and geometric interpretation; overview of normality tests, in particular Lilliefors; EDA tools for assessing a distribution.

Always make a box plot. Always make a QQ plot, make a plot of the CDF and ECDF, make a histogram together with the PDF. These are the typical four plots.

Lecturer L4 99:40

A puzzle from the lecture

Take a sample from any continuous distribution with CDF Transform each value: What is the distribution of The lecturer asked you to think about it and said that the answer does not depend on the distribution of

Check yourselfWhat is the distribution of Y = F(X)? Try to guess first.

The continuous uniform distribution on (0, 1). Proof: and a CDF equal to on is the uniform one. This is the "probability integral transform". It explains why the K-S statistic does not depend on which continuous you test. The chart below shows it.

00.511.500.20.40.60.81Y = F(X) for 2000 simulated valuesdensityuniform density = 1
The result of the puzzle: the histogram of F(X) is flat. (My simulation with X from Ex(0.04).)

Lecture 5 · 13 October 2026

Correlation analysis

How do you measure and test the relationship between two or more variables?

5.1Theory and its sample version

Probability describes a random variable Statistics has only a random sample

  • CDF: and
  • Discrete PMF:
  • Continuous PDF: with
  • Characteristics (mean, variance, standard deviation, median, quartiles, quantiles) are calculated using or
  • Sample statistics výběrové statistiky are transformations of the random sample. So they are random variables with their own distributions.

One variable.

ProbabilityStatistics
Expected value (mean) střední hodnota: or Sample mean výběrový průměr:
Variance rozptyl: Sample variance výběrový rozptyl:
Standard deviation směrodatná odchylka: Sample standard deviation výběrová směrodatná odchylka:

Unbiased estimator is an estimator whose expected value is exactly equal to the theoretical value. Imagine a case that you have 1000 samples from the same population. If you really use 1 over n minus 1 and you evaluate the sample variance on each sample, and take an average of these 1000 values, this will be a good estimator of the variance from the theory.

Lecturer L5 9:01

Two variables. is a 2D random vector with distribution or The data have two columns and rows.

ProbabilityStatistics
Covariance kovariance: Sample covariance výběrová kovariance:
Pearson correlation coefficient korelační koeficient: with Sample Pearson correlation výběrový korelační koeficient: with
In plain words

Greek letters ( are the true values from theory. Latin letters ( are calculated from data. Hypotheses are written with Greek letters, and calculations use Latin letters.

Covariance and correlation from zero

Variance asks how far a value is from its mean, and squares it. Covariance asks about two variables at once: when is above its mean, is above its mean too? Multiply the two deviations and look at the sign.

01234560123456XYX̄ = 3Ȳ = 3both above: product +both below: product +product −product −
Points in the green corners give positive products and push the covariance up. Points in the red corners push it down. Here most of the weight is in the green corners.
Example

Covariance and correlation by hand

Five pairs, with

product
12−2−12
21−1−22
34010
43100
55224
sum008

Covariance: It is positive, so large tends to go with large But the number depends on the units: measure in centimetres instead of metres, and it becomes 100 times larger.

So we remove the units by dividing by both standard deviations. Here so:

A correlation is a covariance on a fixed scale from −1 to 1. So looks strong, but is it real? With only 5 points we need the test below.

5.2Pearson correlation coefficient

  • History: Galton (1880s) studied associations and introduced correlation. Bravais (1844) wrote the first mathematical formula. Karl Pearson (1895) gave the contemporary definition, coming from regression analysis.
  • Also known as the Pearson product-moment correlation coefficient.
  • It measures the strength and direction of linear association between and
  • For interval or ratio data, recommended for bivariate Gaussian data.
  • and are symmetric: order does not matter.
  • is a biased estimator of
  • positive association, as increases, increases. negative association, as increases, decreases.
interpretation
0.0 – 0.2very weak or no association
0.2 – 0.4weak association
0.4 – 0.6moderate association
0.6 – 0.8strong association
0.8 – 1.0very strong or perfect association

No correlation coefficient is a perfect descriptor of the association. Each correlation coefficient was developed to capture typically only one feature of the association. And this Pearson correlation coefficient was developed to capture the linear dependence.

Lecturer L5 19:16

5.3Testing correlation

are nekorelované uncorrelated. are korelované correlated.

Theorem: t-test for correlation

Let be a bivariate random sample of size from a bivariate normal distribution. Under If reject at level p-value: where is the CDF of

  • rejected and correlated, positive association.
  • rejected and correlated, negative association.
  • not rejected and uncorrelated.
  • When the data are not normal, the t distribution is only approximate.
  • When the distribution of is highly skewed, and confidence intervals for are not reliable.

You should start with the decision of the test. If the null hypothesis is not rejected, you end up with the conclusion that these two variables are uncorrelated. There is no reason to interpret the value. Only if you reject the null hypothesis, look at the sign and say whether they are correlated positively or negatively, and look at the absolute value to say whether the strength is weak, moderate or strong.

Lecturer L5 28:43

Fisher z-transformation

To test any value: for a specified against

Theorem (R. A. Fisher, 1921)

For a bivariate normal sample of size under the Fisher z-transform

If reject at level

  • is approximately normal with a stable variance, even for
  • It is often used for calculating confidence intervals for R's cor.test uses for the p-value, and for the confidence interval.

[Near plus or minus one] the distribution of the Pearson correlation is highly skewed, and the lower and upper bound of the confidence interval evaluated from the Student distribution is typically very imprecise.

Lecturer L5 31:35

A confidence interval for a correlation, step by step

Why not simply a margin? Because cannot leave so its distribution is squeezed and skewed near the ends, and such an interval could go past 1. Fisher's idea is to move to a scale where the usual recipe works, build the interval there, and move back.

Example

r = 0.5 with n = 27

  1. Transform
  2. Standard error on the scale:
  3. Interval on the scale: which gives
  4. Transform back with

The interval is not symmetric around 0.5, and that is correct. 0 is outside, so we reject but the true correlation could be weak or strong.

Example

The five points from above: r = 0.8 with n = 5

with Since we do not reject even though looks strong.

R
cor.test(c(1, 2, 3, 4, 5), c(2, 1, 4, 3, 5))
t = 2.3094, df = 3, p-value = 0.1041
95 percent confidence interval:
 -0.2796400  0.9861962
sample estimates:
cor
0.8

The interval runs from about −0.28 to 0.99, so 5 points say almost nothing. Always look at the interval, and not only at

Check yourselfWith and calculate and decide.

and So we reject the variables are correlated, positively, at moderate strength.

5.4Correlation is not independence

Rule

independent uncorrelated (

uncorrelated independent.

Think about the Pearson correlation coefficient: it is a descriptor of linear dependence, only linear. If you know that the two variables are uncorrelated, you cannot say anything about independence, because the only thing you know is that they are not linearly dependent. They can be dependent in many other relationships.

Lecturer L5 37:01
Twelve simulated datasets. Case D is a circle, with r = −0.03, but the variables are clearly dependent. Cases I and J are parabolas with strong r. Cases E and L have nearly the same r, but look different.
  • A, K: random clouds. not rejected.
  • B, C: rotated clouds, moderate
  • D: a circle. yet and are perfectly dependent, in a nonlinear way.
  • E, F, G, H: near lines. tells nothing about the slope, only its direction.
  • I, J: parabolas with unequal sides. Strong but no linear relationship.
  • L: points in a skewed parallelogram. yet not close to one line.

The visualizations are giving you something which is missing in these two numbers. It is the shape of the dependency. Do a statistical test, evaluate the coefficient, make a scatter plot, and merge all the information.

Lecturer L5 45:51

Three famous warnings

Anscombe's quartet (1973): 4 datasets with identical simple statistics: In R: datasets::anscombe.

1: a noisy line. 2: a parabola. 3: a perfect line with one outlier. 4: a vertical line with one outlier that creates all of the correlation.

Datasaurus (Matejka and Fitzmaurice, 2017): 13 datasets, datasauRus::datasaurus_dozen. All have All look uncorrelated in numbers, but the pictures include a dinosaur, a star and a circle.

Same numbers, very different shapes. So uncorrelated does not mean independent.

Simpson's paradox Simpsonův paradox (1951): a trend in several groups disappears or reverses when the groups are combined. Data: 344 penguins of 3 species (Gorman et al., 2014; palmerpenguins::penguins).

Bill length and bill depth, by species.
speciesrp
Adelie0.3911.0e-06
Chinstrap0.6540.0e+00
Gentoo0.6430.0e+00
all together−0.2351.1e-05

Of course, the second conclusion is incorrect, because the information that there are three species of penguins is very important. So the solution is: use as much information as possible from your data set, and make visualizations, not only the calculation of the values.

Lecturer L5 55:54
Check yourselfYou get with Are the variables independent?

You cannot say so. They are uncorrelated, which means there is no sign of a linear relationship. A circle or a parabola can give Look at the scatter plot.

5.5Bivariate normal distribution

A vector has a bivariate normal distribution if its joint density is:

  • Contours (points with equal are concentric ellipses.
  • Vector of expected values: with
  • Variance-covariance matrix kovarianční matice: Variances: Pearson correlation:
  • Linear transformations, marginal and conditional distributions of keep the normality.

The origin of the Pearson correlation can be found exactly in the formula of the bivariate normal density. Directly in the formula there is the Pearson correlation coefficient. This is the reason why everything in the theory is connected with bivariate normality.

Lecturer L5 59:45

Example: and center The directions of the principal axes of the ellipses are the eigenvectors of

-4-2024-3-2-1012345y₁y₂center μ
Contours of this density, computed from the eigenvectors and eigenvalues of Σ.
A simulated sample from a bivariate normal distribution, with the marginal densities of y₁ and y₂.
In plain words

Scatter plots that look like a filled ellipse suggest bivariate normality. Separate clusters, curves or empty centers suggest something else.

5.6Example 1: household expenses

Expenses (thousands CZK per 3 months) for food and beverages, for 7 households, with number of members and net income (thousands CZK per 3 months).

MembersIncomeExpense
410035
28030
412040
13010
515060
312045
413050
R
dat |> ggplot(aes(x = Members, y = Expense)) +
  geom_point(size = 3.5) +
  stat_ellipse(level = 0.95, type = "norm", segments = 100)
dat |> GGally::ggpairs()
The 95 % confidence ellipse from the bivariate normal distribution, and the matrix of scatter plots. Points inside the ellipse with no clusters are a visual sign of bivariate normality.
Example

Test the correlation of members and expenses

R
cor(dat$Members, dat$Expense)
[1] 0.8896204
cor.test(dat$Members, dat$Expense)
        Pearson's product-moment correlation
t = 4.3557, df = 5, p-value = 0.00732
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 0.4137446 0.9836776
sample estimates:
      cor
0.8896204

and of no correlation is rejected: expenses and the number of members are very strongly positively correlated.

By hand:

Both tests reject

T under H₀: t(5)
00.10.20.30.4-4-20242.5714.356
Fisher z statistic under H₀: N(0, 1)
00.10.20.30.4-4-20241.962.84

5.7Covariance and correlation matrices

Take observations of variables in a matrix. is the -th observation of variable Rows are the -dimensional observations, and columns are the random samples of each variable.

Sample variance-covariance matrix výběrová kovarianční matice Sample correlation matrix výběrová korelační matice
Containssample covariances of all pairssample correlations of all pairs
Shapesquare symmetric, positive definitesquare symmetric
Diagonalsample variances ones
Check yourselfWhy does the correlation matrix always have ones on the diagonal?

The diagonal is the correlation of a variable with itself. Put in the formula:

In R

sample statisticfunction
sample meanmean(X)
sample variancevar(X)
sample standard deviationsd(X)
sample covariancecov(X, Y)
sample correlationcor(X, Y)
correlation testcor.test(X, Y)
sample variance-covariance matrixcov(Z)
sample correlation matrixcor(Z)
scatterplotsGGally::ggpairs
correlogramGGally::ggcorr, ggcorrplot::ggcorrplot
Example

The matrices for Example 1

R
dat |> cov()
          Members    Income   Expense
Members  1.904762   50.2381  19.64286
Income  50.238095 1561.9048 623.80952
Expense 19.642857  623.8095 255.95238
dat |> cov() |> diag() |> sqrt() |> round(digits = 2)   # standard deviations
Members  Income Expense
   1.38   39.52   16.00
dat |> cor() |> round(digits = 2)
        Members Income Expense
Members    1.00   0.92    0.89
Income     0.92   1.00    0.99
Expense    0.89   0.99    1.00
dat |> ggcorrplot::cor_pmat() |> round(digits = 3)      # p-values
        Members Income Expense
Members   0.000  0.003   0.007
Income    0.003  0.000   0.000
Expense   0.007  0.000   0.000

Check: ✓

This is the general way to calculate the sample standard deviations. Do not write any loops. Think about what will happen if I give you 1000 dimensional data. Think about writing pieces of code which are really very general.

Lecturer L5 73:49

A correlogram is a picture of the correlation matrix: colors from blue (near −1) through white (near 0) to red (near +1). Non-significant cells are crossed out. Use it together with the matrix of scatter plots.

Example 1: the scatter plots and the correlogram.

I really suggest to use some visualizations which are capable to use also the matrix of the p-values, to indicate by some crossings the cases where the test decision was: not reject the null hypothesis. This is the complete information.

Lecturer L5 76:29

Example 2. 20 children of different ages in pedagogical-psychological research: Age, Memory score, IQ score, Reading score.

Scatter plots and the correlogram for Example 2. IQ is not significantly correlated with any other variable.

5.8Spearman's rank correlation

What if the data are ordinal or not bivariate normal? Calculate Pearson's correlation on the ranks.

Definition

For samples and with ranks and the sample Spearman's rank correlation coefficient Spearmanův výběrový pořadový korelační koeficient is:

If no average ranks are used:

  • It quantifies rank correlation between and
  • It is a nonparametric analogy of Pearson correlation.
  • It is typically used for ordinal or non-Gaussian data, even when only rankings are known (final grades, sport results).
  • In R: cor(..., method = "spearman"), cor.test(..., method = "spearman"), ggcorrplot::cor_pmat(..., method = "spearman").
Theorem: test of rank correlation

against meaning and are pořadově korelované rank-correlated.

  • Under If reject
  • Under If reject at asymptotic level
Example

Spearman for Example 1

35304010604550
4241534
1008012030150120130
= rank of 3241756
= rank of 5251735
= rank of 324.5174.56

Three households have 4 members, at positions 4, 5, 6, so each gets average rank 5. Then

R
# cor(dat$Members, dat$Expense, method = "spearman")
cor.test(dat$Members, dat$Expense, method = "spearman")
        Spearman's rank correlation rho
S = 10.339, p-value = 0.0254
sample estimates:
      rho
0.8153742
# cor.test(dat$Members, dat$Expense, method = "spearman", exact = FALSE)

Time to time you can see some warning when calculating the Spearman's correlation test, typically if there are some ties. If you want to be sure which version is used, use exact equal to false or exactly equal to true. This is only an information that some adjustment must be done.

Lecturer L5 84:36

Pearson and Spearman compared. Crossed-out cells are not significant at 5 %. I calculated the crossing with the t formula above.

Pearson
MembersIncomeExpense
Members10.920.89
Income0.9210.99
Expense0.890.991
Spearman
MembersIncomeExpense
Members10.860.82
Income0.8610.99
Expense0.820.991
Example 1. The two methods give nearly the same picture, as the data are close to bivariate normal.
Pearson
AgeMemoryIQReading
Age10.72-0.20.85
Memory0.7210.30.82
IQ-0.20.310.15
Reading0.850.820.151
Spearman
AgeMemoryIQReading
Age10.7800.88
Memory0.7810.340.8
IQ00.3410.21
Reading0.880.80.211
Example 2. Small differences, but the same conclusion.

If you can assume that all the pairs follow the bivariate normal distribution, you are safe to use the Pearson's correlation. If you are not sure about the normality, use rather the Spearman's correlation.

Lecturer L5 87:21
Check yourselfWhen would you prefer Spearman to Pearson?

For ordinal data, or when the data are far from bivariate normal.

5.9Kendall's tau

A completely different idea: count the pairs of observations that agree in order.

Two observations and are:

  • concordant if both go in the same direction;
  • discordant if they go in opposite directions.

Some pairs can be neither, because of ties.

Definition: Kendall's tau

The sample Kendall's rank correlation coefficient Kendallův výběrový korelační koeficient:

  • number of all pairs.
  • number of concordant pairs. number of discordant pairs.
  • Corrections for ties: and where are the counts of tied values in and Otherwise or
  • It quantifies ordinal association.
  • It does not consider the distance between ranks, only the ordering.
  • It is typically used for ordinal data, and especially to compare two types of ranking.
  • is the number of inversions needed to rearrange the -ranking into the -ranking.
Theorem: test of ordinal association

against

With no ties, if reject at asymptotic level For small or ties, an adjusted formula is used.

In R: cor(..., method = "kendall"), cor.test(..., method = "kendall"), ggcorrplot::cor_pmat(..., method = "kendall"), ppcor::pcor.

I remember that it is widely used in the banks. They assign you some score, one number, and they can have different algorithms. They use Kendall's tau to compare the different rankings, different algorithms, different scores.

Lecturer L5 92:34
Example

Kendall for Example 1, Members and Expense

  • pairs.
  • concordant: all except households 1-3, 1-6, 1-7, 3-6, 3-7.
  • discordant: 1-6 and 3-6.
  • Pairs 1-3, 1-7 and 3-7 are ties in (all have 4 members): neither concordant nor discordant.
  • Ties: three values of 4 in so and
R
# cor(dat$Members, dat$Expense, method = "kendall")
cor.test(dat$Members, dat$Expense, method = "kendall")
        Kendall's rank correlation tau
z = 2.1954, p-value = 0.02814
sample estimates:
      tau
0.7200823
Summary: three coefficients on the same data (Members and Expense).
CoefficientWorks onMeasuresUse forExample 1p
Pearson valueslinear associationinterval/ratio data, bivariate normal0.8900.0073
Spearman ranksmonotonic (rank) associationordinal or non-Gaussian0.8150.0254
Kendall pairs, order onlyordinal associationordinal, comparing rankings0.7200.0281
Check yourselfWith observations, how many pairs are compared?

pairs.

5.10Partial and multiple correlation

With at least 3 variables you can ask three different questions.

Think of each circle as the information in one variable. The orange area is what each coefficient measures.
CoefficientQuestionNotation
Pearsonbetween and ignoring
Partialbetween and excluding the effect of
Multiplebetween and the set
In plain words

Reading the notation: two variables before the dot: partial. One variable before the dot: multiple.

Having at least three variables, the classical Pearson correlation between two variables includes also everything which is possibly shared by all the other variables. If you want to exclude such information, if you want to capture only information really between Z1 and Z2, you need something different, so called partial correlation.

Lecturer L5 95:47

5.11Partial correlation

Definition

The coefficient of partial correlation koeficient parciální korelace quantifies the association between and excluding the effect of The sample version:

  • Values lie in they show both strength and direction.
  • is a biased estimator of

The general calculation

For variables with data matrix of size let Its inverse is the precision matrix. Let be the diagonal matrix of The matrix of sample partial correlations of all pairs, excluding the effect of all other variables, is:

R
R_inv <- solve(cor(Z))
D <- sqrt(diag(R_inv))
R_part <- -R_inv / outer(D, D)
diag(R_part) <- 1

The test

Theorem

against For a sample of size from an -dimensional normal distribution, with the sample partial correlation, under If reject p-value:

R
d <- nrow(Z) - ncol(Z)
T <- (R_part * sqrt(d)) / sqrt(1 - R_part^2)
p_part <- 2 * (1 - pt(abs(T), df = d))
diag(p_part) <- 0

It is an analog of the Pearson correlation test, leading to a student's t test. The only difference is that it does not have n minus two but n minus m degrees of freedom. You can find some packages in R where it is implemented, but they are rather old and there are some bugs. So I think it is much safer to use your own piece of code.

Lecturer L5 100:03
Example

Pearson against partial correlations

Pearson
MembersIncomeExpense
Members10.920.89
Income0.9210.99
Expense0.890.991
Partial
MembersIncomeExpense
Members10.58-0.3
Income0.5810.94
Expense-0.30.941
Example 1. Members and Income are 0.92 in Pearson but not significant in partial. Expense and Income stay strong. So income is the direct driver of expenses.
Pearson
AgeMemoryIQReading
Age10.72-0.20.85
Memory0.7210.30.82
IQ-0.20.310.15
Reading0.850.820.151
Partial
AgeMemoryIQReading
Age10.39-0.690.69
Memory0.3910.480.28
IQ-0.690.4810.38
Reading0.690.280.381
Example 2. Age and IQ: not significant in Pearson, but −0.69 in partial.

The crossed-out cells here are my calculation using the t formula, with df = n − 2 for Pearson and df = n − m for partial.

Example 3. 16 economic indicators of European countries.

Pearson correlations.
Partial correlations. The bright block of −1 covers the sector shares of GDP.
Check yourselfWhy are there values of −1 in the block of Agriculture, Manufacturing, Civil Engineering, Trade, Finance and Other?

This is my interpretation: these variables are shares of the same total, so they must sum to a constant. Each one is then almost fully determined by the others. So the partial correlations reach ±1.

How to read the comparison

PearsonpartialInsight
strongstrongTrue independent relationship.
strongnot significantSpurious or mediated: a fake relationship, driven by a shared confounder, or fully mediated by other variable(s).
not significantstrongSuppressed: a true underlying relationship masked or cancelled by other variable(s).
strongstrong, opposite directionSimpson's paradox or confounding effect: the direction of the raw relationship is an illusion, driven entirely by other variable(s).

If Pearson is strong but the partial is close to zero, this is called spurious correlation. It is a fake correlation. It is not direct between the two variables, it is caused by the other variables. There is a web page by Tyler Vigen called spurious correlations, with more than 1,000 pairs of variables of real data where the p-value is very small. You can laugh at many data sets.

Lecturer L5 103:24
Check yourselfPearson correlation is strong, but the partial correlation is not significant. What does this suggest?

A spurious or mediated relationship. It is driven by a shared confounder, or passes through other variables.

5.12Multiple correlation

Definition

The coefficient of multiple correlation koeficient mnohonásobné korelace quantifies the association between and a set of variables It is the highest Pearson correlation between and any linear combination of

The sample version: where

  • Values lie in only the strength of association, with no direction.
  • It is a biased estimator: it systematically overestimates the true value.
  • The more variables in the higher the value, even if there is no actual relationship with

Multiple correlation is not a classical correlation. It is just a value between zero and one. It has no information about the direction. It carries only information whether there is some association.

Lecturer L5 105:31

Calculation

Let Let be the submatrix of correlations between and

For 3 variables:

R
R <- cor(Z)
R_star <- R[-1, -1, drop = FALSE]
r_star <- R[-1,  1, drop = FALSE]
r_mult <- sqrt(drop(t(r_star) %*% solve(R_star, r_star)))

The test

Theorem

against For a sample of size from an -dimensional normal distribution, under If reject p-value:

Example

Example 2: IQ against the other three variables

R
R <- cor(dat2)
colnames(R)
[1] "Age"     "Memory"  "IQ"      "Reading"
i <- 3
R_star <- R[-i, -i, drop = FALSE]
r_star <- R[-i,  i, drop = FALSE]
r_mult <- sqrt(drop(t(r_star) %*% solve(R_star, r_star)))
print(r_mult)
[1] 0.7310867

The sample multiple correlation between IQ and the other 3 variables is 0.73, while the single Pearson correlations of IQ are only −0.2, 0.3 and 0.15.

My extra step, the test: and so is rejected.

Check yourselfCan an individual Pearson correlation be larger than the multiple correlation?

No (for its absolute value). The multiple correlation is the maximum over all linear combinations, and using a single variable is one such combination. So for every

Summary list from the lecture. Theoretical characteristics and their sample analogues. Sample Pearson correlation: definition, calculation, test, interpretation and usage. Rank-based coefficients: definition, calculation, interpretation, usage, comparison, concordant and discordant pairs. Sample variance-covariance and correlation matrix, correlogram, scatterplots. Sample partial and multiple correlation: definition, interpretation and usage.

Check yourselfCan a multiple correlation be negative?

No. Its values lie in It shows only strength, with no direction.

Lecture 6 · 20 October 2026

Regression analysis

How do you describe how depends on one or more predictors, and how do you predict new values?

Watch out

No transcript was available for this lecture, so it has no lecturer quotes.

6.1Multivariate normal distribution

This is the probability model behind regression.

The 2rozměrné normální bivariate normal distribution was introduced in Lecture 5. Here and The contours are concentric ellipses with center and the principal axes are the eigenvectors of

Important property

In the multivariate normal distribution, independence is equivalent to uncorrelation of the variables. This is special. Usually, uncorrelated does not imply independent.

Example: The contours are circles.

-4-202-4-3-2-10123456y₁y₂center μ
Independent variables with equal variances give circular contours.

n dimensions

A random vector has the n-rozměrné normální -variate normal distribution if its joint density is:

  • is an vector, with
  • is a symmetric positive definite matrix. is the variance of is the Pearson correlation.

Three useful facts. Let

  • Linear transformations stay normal. If is a matrix with rank and is a vector, then
  • In particular, for an vector and a number
  • Conditional distributions stay normal. If is a subset of of size and the complementary subset with given values then

If are mutually independent with the same variance then is diagonal, and:

6.2The regression model

In plain words

You will need: sums of squares, confidence intervals and the t-test. Regression fits a straight line through a cloud of points: is the height of the line at is the slope: how much changes on average when grows by 1. The matrices below only write this idea for many variables at once. The worked example under Least squares does the simple case by hand.

Simple regressionMultiple regression
Studiesa predictor and an observed random variable predictors and an observed
Model where is the regresní funkce regression function, linear in its parameters
Data pairs vectors

is the random error.

Matrix form

Write the model for all observations:

The model in one line
  • an vector of observations, random variables.
  • a vector of regression coefficients.
  • the design matrix matice plánu, with Its columns are predictors with fixed values. It reflects the design of the model.
  • the linear approximation of by the predictors.
  • an vector of náhodné chyby random errors.

Assumptions on random errors

Assumption on errors Equivalent statement on
nonsystematic: so
homogeneous variance:
mutually uncorrelated: for for
diagonal matrix:

What "linear" means

The model must be linear in the parameters not necessarily in All of these are linear models:

simple, linear function
simple, quadratic function
simple, polynomial function
simple, exponential function
multiple, 2 predictors
multiple, predictors

6.3Least squares

Fitted value Ŷ₁ on the line, observed Y₁, and residual r₁ = Y₁ − Ŷ₁. Also the split of Y₅ − Ȳ into a residual and a part explained by the line.

Choose to make the sum of squared vertical distances as small as possible.

The least-squares (LS) method metoda nejmenších čtverců is the optimization The stationary point is given by:

The normal equations are So:

The least-squares estimator

odhad metodou nejmenších čtverců

The residual sum of squares reziduální součet čtverců is the lowest achievable value of

Example

The line by hand, without matrices

With one predictor, the matrix formula becomes two simple ones:

So the slope is covariance divided by variance, and the line always goes through the point For the household data in the tool above, with

  • Slope: When income grows by 1, expense grows by 0.40 on average.
  • Intercept: This is the predicted expense at income 0, which is far from any of the data, so do not read much into it.
  • Fitted value at income 100:
  • Error variance: so and
  • so The line explains 97 % of the variability in expense.

Quantities that follow.

  • Fitted values vyrovnané hodnoty: points on the regression function: so
  • Residuals: observed minus fitted: so
  • Residual sum of squares:
  • Regression sum of squares regresní součet čtverců:
  • Best linear approximation of by

This is the same split as in ANOVA: Total = explained + unexplained.

Properties

  • Each is a linear function of
  • is unbiased:
  • It depends on the unknown
Gauss-Markov theorem

has the lowest variance among all linear unbiased estimators. It is the best linear unbiased estimator (BLUE) nejlepší nestranný lineární odhad of

Estimating the error variance.

Theorem

is the best unbiased estimator of with the lowest variance. And

In plain words

Why We use values, but we estimated coefficients. Each estimate costs one degree of freedom. It is the same idea as in Lecture 1.

Check yourselfWhat exactly does the least-squares method minimize?

The sum of squared vertical distances between observed and fitted values:

6.4Adding normality: tests and intervals

Now assume and Then uncorrelated errors are also independent, and we can find the distribution of the estimators.

Theorem: distribution of LS estimators
  • and are independent.

Test of overall regression (omnibus)

against there exists with

Theorem

Under independent of Hence, under If reject

This is basically the same F-test as in one-way ANOVA. Compare it with the omnibus F-test.

Test of one coefficient

against for a specified

Theorem

where is the -th diagonal value of If reject

Confidence intervals and regions

  • CI for
  • joint confidence region for the vector the set of with
  • CI for
  • CIs and tests for subsets and linear combinations of coefficients can be derived too.
In plain words

The first line is the usual recipe again. is the estimate, is its standard error (R calls it Std. Error), and the critical value comes from With one predictor, is simply So the slope is known more precisely when there is less noise, more data, and a wider range of

Example

CI for the household slope, by hand

and So which gives

0 is outside the interval, so income does affect expense. The t-test agrees:

Check yourselfA coefficient has Estimate 0.5 and Std. Error 0.1. What is the t value? And if

And

6.5Example: weight and height, model m1

Idea: fit a straight line,

528 people, weight against height.
R
m1 <- lm(Weight ~ 1 + Height, data = dat)
print(summary(m1), signif.stars = FALSE)
Residuals:
    Min      1Q  Median      3Q     Max
-12.277  -3.832  -1.121   3.487  18.685
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  32.9708     3.4759   9.485   <2e-16
Height        0.2296     0.0205  11.201   <2e-16
Residual standard error: 5.26 on 526 degrees of freedom
Multiple R-squared:  0.1926,  Adjusted R-squared:  0.1911
F-statistic: 125.5 on 1 and 526 DF,  p-value: < 2.2e-16
Line in the outputHow to read it
Estimate Fitted function: One extra cm adds 0.23 kg on average.
t value Estimate / Std. Error:
Pr(&gt;|t|)p-value of Both coefficients are significant.
Residual standard error estimated standard deviation of random errors. df
Multiple R-squaredThe model explains 19.26 % of the variability.
F-statisticThe overall test: the model is significant.

Inspect the design matrix.

R
slice_head(dat, n = 6)
  ID    Sex Height Weight   BMI
1  1 female  173.4   67.7 22.52
2  2   male  160.1   71.3 27.82
3  3 female  165.2   66.3 24.29
4  4 female  164.1   65.5 24.32
5  5   male  160.9   60.3 23.29
6  6 female  179.6   69.0 21.39
head(model.matrix(m1), n = 6)
  (Intercept) Height
1           1  173.4
2           1  160.1
3           1  165.2
4           1  164.1
5           1  160.9
6           1  179.6

The first column of ones belongs to and the second holds the heights.

Estimates and intervals.

R
coefficients(m1)
(Intercept)      Height
 32.9707696   0.2296542
confint(m1, level = 0.95)
                 2.5 %    97.5 %
(Intercept) 26.1423430 39.799196
Height       0.1893774  0.269931
vcov(m1)                 # the estimate of Cov(beta-hat)
            (Intercept)        Height
(Intercept) 12.08214922 -0.0711106783
Height      -0.07111068  0.0004203521

Check: the standard error of Height. And the interval by hand: which gives as confint says. In words: with 95 % confidence, one extra centimetre goes with 0.19 to 0.27 kg more on average.

95 % CIs for β₀ and β₁ (the cross) and the joint 95 % confidence region (the ellipse). The ellipse is thin and tilted because the two estimates are strongly negatively correlated: a higher intercept goes with a lower slope.

6.6Confidence and prediction intervals

Let be a response for predictor values Let

Confidence intervalPrediction interval predikční interval
Forthe expected value the regression function at a future observation at
Formula
Includesvariability of LS estimates onlyvariability of LS estimates and of the individual value (the error variance)

So the PI is always wider than the CI at the same predictor value.

In plain words

CI: where is the average weight of all people who are 170 cm tall? PI: what will the weight of one new person of 170 cm be? One person varies more than an average.

The fitted line, the narrow 95 % CI band and the wide 95 % PI band. Both are narrowest near the mean height.
Example

Both intervals by hand, at income 100

For simple regression, It is smallest at and grows as you move away, which is why the bands bend outwards.

Household data: with fitted value and

CalculationResultQuestion it answers
CIWhat is the average expense of all households with income 100?
PIWhat will the expense of one new household with income 100 be?
fitted line95 % confidence band95 % prediction band
02040608020406080100120140160incomeexpense
The same two intervals at every income. More data would shrink the confidence band towards the line, but the prediction band would never get narrower than about ±1.96 s, because one household always varies.
R
predict(m1, newdata = new.data, se.fit = TRUE, interval = "confidence")
predict(m1, newdata = new.data, se.fit = TRUE, interval = "prediction")
Check yourselfWhich interval is wider at the same and why?

The prediction interval. It includes the uncertainty of the fitted line and the random error of one new observation: instead of

6.7Adding a dummy variable: model m2

Weight against height, colored by sex.

Sex is a factor. In the model it becomes a dummy variable: 1 for male, 0 for female. Now we fit 2 parallel lines.

R
m2 <- lm(Weight ~ 1 + Height + Sex, data = dat)
print(summary(m2), signif.stars = FALSE)
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -3.49961    3.08872  -1.133    0.258
Height       0.42108    0.01761  23.905   <2e-16
Sexmale      8.29905    0.39340  21.096   <2e-16
Residual standard error: 3.873 on 525 degrees of freedom
Multiple R-squared:  0.563,  Adjusted R-squared:  0.5614
F-statistic: 338.2 on 2 and 525 DF,  p-value: < 2.2e-16
  • The model is significant. and are significant. is not.
  • Fitted for females: For males: (This leaves out the non-significant intercept.)
  • much better than 5.26. jumps from 0.19 to 0.56.
  • Interesting: the Height coefficient rose from 0.23 to 0.42 once Sex was included.
femalemale
60708090150160170180190200height (cm)weight (kg)same slope, 8.3 kg higher
Model m2 drawn from the estimates above, including the intercept −3.5.

The design matrix with a dummy.

R
head(model.matrix(m2), n = 6)
  (Intercept) Height Sexmale
1           1  173.4       0
2           1  160.1       1
3           1  165.2       0
4           1  164.1       0
5           1  160.9       1
6           1  179.6       0
Check yourselfGuess the design matrix when a factor has more than 2 levels.

A factor with levels gets dummy columns. The reference level has zeros in all of them. For Diet A, B, C: columns DietB and DietC. Diet A rows have (0, 0), B rows (1, 0), C rows (0, 1). This is exactly the reference group model from Lecture 2.

95 % CIs and joint regions for pairs of coefficients in m2.
Regression function, 95 % CIs and PIs for each sex.
Check yourselfUse model m2 to predict the weight of a man and a woman who are 170 cm tall.

Woman: kg. Man: add 8.3 kg, so about 76.4 kg.

6.8A more complex function: models m3 and m4

m3, a quadratic term.

R
m3 <- lm(Weight ~ 1 + Height + I(Height^2) + Sex, data = dat)
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.204e+01  2.678e+01  -0.450   0.6531
Height       5.224e-01  3.159e-01   1.654   0.0988
I(Height^2) -2.991e-04  9.311e-04  -0.321   0.7482
Sexmale      8.298e+00  3.937e-01  21.076   <2e-16
Residual standard error: 3.877 on 524 degrees of freedom
Multiple R-squared:  0.5631,  Adjusted R-squared:  0.5606
F-statistic: 225.1 on 3 and 524 DF,  p-value: < 2.2e-16

The model is significant, but only is. The regression function is too complex. Height and Height² carry nearly the same information, so neither looks useful alone.

Model m3: almost the same picture as m2. The extra term brought nothing.
Watch out

In R, I(Height^2) is needed. Inside a formula, ^ has a different meaning, and I() says "calculate this as ordinary arithmetic".

m4, an interaction. The slope may differ by sex.

R
m4 <- lm(Weight ~ 1 + Height * Sex, data = dat)
               Estimate Std. Error t value Pr(>|t|)
(Intercept)    -0.81099    4.22719  -0.192    0.848
Height          0.40570    0.02414  16.806   <2e-16
Sexmale         2.74879    5.96981   0.460    0.645
Height:Sexmale  0.03290    0.03531   0.932    0.352
Residual standard error: 3.874 on 524 degrees of freedom
Multiple R-squared:  0.5637,  Adjusted R-squared:  0.5612
F-statistic: 225.7 on 3 and 524 DF,  p-value: < 2.2e-16

The model is significant, but only is. The regression function is too complex. The interaction is not significant ( so the lines may be treated as parallel.

femalemale
60708090150160170180190200height (cm)weight (kg)slopes 0.406 and 0.439: almost parallel
Model m4 drawn from the estimates above.
Model m4 with CIs and PIs.

6.9Coefficient of determination

R-squared
  • Meaning: how much of the total variability of is explained by the model and predictors. Often written as a percentage.
  • It measures performance on the learning data: how well the model fits them.
  • If and then
  • If all then
  • the squared sample Pearson correlation between observed and fitted

Adjusted R-squared

Adding any predictor can never decrease and it typically increases it. This can cause overfitting. The main aim is a reasonably good and simple model that also works for new, similar data, and not an almost perfect model for your learning data.

Adjusted R-squared
  • The fraction penalizes each added predictor.
  • is a performance measure, suitable for comparing different models on the same dataset.
  • Other measures: logaritmická věrohodnost log-likelihood, Akaike information criterion (AIC), Bayes information criterion (BIC).
Example

Check with m2

✓

Check yourself and with and Find and

6.10Comparing models

ANOVA compares a model with its submodel(s). Each row asks: did the added term significantly reduce the residual sum of squares?

R
print(anova(m1, m2, m3), signif.stars = FALSE)
Model 1: Weight ~ 1 + Height
Model 2: Weight ~ 1 + Height + Sex
Model 3: Weight ~ 1 + Height + I(Height^2) + Sex
  Res.Df     RSS Df Sum of Sq        F Pr(>F)
1    526 14554.1
2    525  7876.9  1    6677.2 444.2775 <2e-16
3    524  7875.4  1       1.6   0.1032 0.7482
print(anova(m1, m2, m4), signif.stars = FALSE)
Model 3: Weight ~ 1 + Height * Sex
  Res.Df     RSS Df Sum of Sq        F Pr(>F)
1    526 14554.1
2    525  7876.9  1    6677.2 444.9259 <2e-16
3    524  7863.9  1      13.0   0.8682 0.3519

Adding Sex helps a lot ( Adding Height² or the interaction after that does not help (

Three ways to compare models on the same dataset:

  • adjusted R-squared
  • ANOVA (for a model and its submodels only),
  • Akaike information criterion
modelR²adj. R²logLikAIC
m10.1930.191−16253256
m20.5630.561−14632933
m30.5630.561−14632935
m40.5640.561−14622934

We should choose m2. It has the lowest AIC, and it is the simplest of the good models.

Check yourselfCan anova() compare m3 and m4 directly?

No. ANOVA needs a model and its submodel, and neither is a submodel of the other: m3 has Height², and m4 has the interaction. Use adjusted R² or AIC.

6.11Multiple regression on household data

Back to the 3D household data.

Scatter plots of members, income and expense.
R
m <- lm(Expense ~ 1 + Income + Members, data = dat)
print(summary(m), signif.stars = FALSE)
Residuals:
      1       2       3       4       5       6       7
-0.6157  0.3914 -4.5427  1.2489  3.5268 -1.0026  0.9938
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -3.17942    3.48326  -0.913  0.41300
Income       0.44635    0.08085   5.521  0.00526
Members     -1.45998    2.31513  -0.631  0.56252
Residual standard error: 3.048 on 4 degrees of freedom
Multiple R-squared:  0.9758,  Adjusted R-squared:  0.9637
F-statistic: 80.66 on 2 and 4 DF,  p-value: 0.0005855

Fitted function:

Look at Members: alone, it had with Expense. Here it is not significant, and even negative. Once you know income, knowing the number of members adds nothing. It agrees with the partial correlation in Lecture 5.

The graph of the best linear approximation is a -dimensional nadrovina hyperplane in a -dimensional space.

With two predictors, the fit is a plane in 3D.

6.12Correlation coefficients through regression

Regression explains all the correlations from Lecture 5.

Recall the three ideas: Pearson, partial and multiple correlation.
The Pearson and partial correlograms of the household data, again.

Pearson correlation and R-squared

is the association between and is the share of variability of explained by from lm(Z1 ~ 1 + Z2).

Rule

Multiple correlation and R-squared

is the association between and is the share of variability of explained by and from lm(Z1 ~ 1 + Z2 + Z3).

Rule

Generally, the multiple correlation is the Pearson correlation between and its best linear approximation by

R
# 1. Build the appropriate model
model.M <- lm(Expense ~ 1 + Income + Members, data = dat)
# 2. Take the fitted values
fitted.M <- fitted.values(model.M)
# 3. Evaluate the Pearson correlation
cor(dat$Expense, fitted.M)
[1] 0.9878276
sqrt(summary(model.M)$r.squared)
[1] 0.9878276

Partial correlation and R-squared

Rule
In plain words

Take the variability of that could not explain (the denominator). What share of it does explain in addition (the numerator)?

The same rule as areas in the circles.

Generally, the partial correlation is the Pearson correlation between the residuals of two models. Remove the effect of the other variables from both, then correlate what is left:

M1: lm(Z1 ~ 1 + Z3 + ... + Zm) gives residuals M2: lm(Z2 ~ 1 + Z3 + ... + Zm) gives residuals Then

R
# 1. Build the two appropriate models
model.M1 <- lm(Expense ~ 1 + Income, data = dat)
model.M2 <- lm(Members ~ 1 + Income, data = dat)
# 2. Take their residuals
r1 <- residuals(model.M1)
r2 <- residuals(model.M2)
# 3. Evaluate the Pearson correlation
cor(r1, r2)
[1] -0.3007187
sqrt((summary(model.M)$r.squared - summary(model.M1)$r.squared) /
     (1 - summary(model.M1)$r.squared))
[1] 0.3007187
R_part["Expense", "Members"]
[1] -0.3007187
Example

The numbers behind the R² formula

and So and The square root loses the sign, so take the sign from the residual correlation or the partial correlation matrix:

Summary list from the lecture. Linear regression model: general idea, simple linear regression, predictor and observed variable. Multiple linear regression model: predictors and observed variable, matrix equation, assumptions on errors and observations, regression coefficients, design matrix. Least-squares method: the idea, estimators and properties (BLUE). Coefficient of determination: R-squared, adjusted R-squared, interpretation and usage. Relationship between R-squared in suitable models and Pearson, multiple and partial correlation.

Reference

Tools for the exam

Which test should I use?

Start from your question. Then check the assumptions. The right-hand column is the fallback when normality fails.

QuestionDataParametric testNonparametric test
How precise is my estimate?anya confidence interval for that parameter. Most test functions in R report one.
Is the mean or median equal to a given value?one sampleone-sample t-test t.testsymmetric: Wilcoxon signed-rank wilcox.test
skewed: sign test binom.test
Did something change, before and after?two paired samplespaired t-test (t-test on differences)paired Wilcoxon or sign test on the differences
Do two groups differ?two independent samplestwo-sample t-test, WelchMann-Whitney wilcox.test, permutation test
Do 3+ groups differ?one factorone-way ANOVA aov, then Tukey
unequal variances: Welch's ANOVA oneway.test
Kruskal-Wallis agricolae::kruskal, then Mann-Whitney with Bonferroni
many outliers: median test
Effects of two factors?two factorstwo-way ANOVA aov(y ~ A * B)
Do data follow a given distribution?one sampleany, grouped: Pearson χ²
continuous and fully specified: Kolmogorov-Smirnov ks.test
Are the data normal?one sampleShapiro-Wilk shapiro.test, Lilliefors nortest::lillie.test. Not K-S with estimated parameters!
Do two samples have the same distribution?two samplestwo-sample K-S, or Mann-Whitney in its general form
Are variances equal?groupsBartlett bartlett.test, only with normal dataLevene car::leveneTest
Are two variables related?two numeric variablesPearson cor.testSpearman, Kendall (method =)
Related, removing the effect of others?3+ variablespartial correlation
Predict from numeric linear regression lm

How to write a test result

  1. State and in words and symbols.
  2. Say which test, and why its assumptions hold. Fix first.
  3. Report the statistic, df and p-value.
  4. Decide: " so we reject " or " so we do not reject ". Never " is true".
  5. Write the conclusion in plain language about the real question.
  6. Look at a plot, and check that the result makes sense.

Formula sheet

TopicFormula
Sample variance, SD
Standard error of a mean estimated by
Any test statistic
Any confidence intervalestimate critical value standard error
CI for a mean
CI for a difference (Welch)
CI for a proportion, large
CI for a variance
Sample size for margin rounded up
Standardization
Familywise error
Sum of squares df:
ANOVA F
CI for group mean
Sign test
Signed-rank
Mann-Whitney
Kruskal-Wallis
Pearson χ² with
K-S
Pearson correlation
Fisher z variance
Spearman, no ties
Kendall with
Partial correlation
Multiple correlation test
Least squares
Coefficient test
R²

Corrections to the lecture material

I checked the formulas against each other and against standard theory. These look like small typing errors, and this guide uses the corrected form. This is my reading, so it is worth confirming with the lecturer, because corrected materials may exist.

TopicIn the materialUsed here
Meaning of a confidence interval"contains the true value with given probability"the same, read as a statement about the method before the data are known. See what 95 % means.
Chi-squared with estimated mean with nothing after the sum
Critical region, lower one-sided
Diets, critical region plotdrawn with df 51.86 (the lecturer said so)df 48.86
ANOVA notationgroup mean sums to rows have sum to
Cell means model
Between-groups df
Reference group model is the difference of from from
Sign test, large samples"test statistic "
Restart time exampleone title has as in the analysis
Kolmogorov-Smirnov next to an approximation that fits itself
Cramér-von Mises
History of correlationKarl Pearson (1985)1895
Partial correlation twicesecond is
Multivariate normalmixes and vector sizes
Test of one coefficient
Confidence and prediction intervals

Glossary: English and Czech

Czech terms for the lectures come from the lecture material. Those for Statistics from zero are standard translations that I added.

EnglishCzech
alternative hypothesisalternativní hypotéza
analysis of variance (ANOVA)analýza rozptylu
between-groups sum of squaresregresní
central limit theoremscentrální limitní věta
coefficient of multiple correlationkoeficient mnohonásobné korelace
coefficient of partial correlationkoeficient parciální korelace
confidence intervalinterval spolehlivosti
confidence interval (CI)interval spolehlivosti
Covariancekovariance
critical regionkritická oblast
cumulative distribution functiondistribuční funkce
Descriptive statisticspopisná statistika
design matrixmatice plánu
effectefekt
empirical CDF (ECDF)empirická distribuční funkce
Estimateodhad
estimatorodhad
exchangeabilityzaměnitelnost
Expected (theoretical) frequenciesteoretické četnosti
expected valuestřední hodnota
Expected value (mean)střední hodnota
Exploratory data analysis (EDA)exploratorní analýza dat
Fitted valuesvyrovnané hodnoty
grand meancelkový průměr
group meanskupinový průměr
Homogeneity of variancehomogenita rozptylu
interaction effectinterakce
Intervalintervalová
least-squares (LS) methodmetoda nejmenších čtverců
linear contrastkontrast
machine / statistical learningstrojové / statistické učení
main effecthlavní efekt
mathematical statisticsmatematická statistika
modemód
multinomial distributionmultinomické rozdělení
Nominalnominální
normal distributionnormální rozdělení
null hypothesisnulová hypotéza
Observed (empirical) frequenciesempirické četnosti
one-way ANOVAjednofaktorová analýza rozptylu / jednoduché třídění
order statisticpořádková statistika
ordered sampleuspořádaný výběr
Ordinalordinální
outliersodlehlé hodnoty
p-valuep-hodnota
Parameterparametr
Pearson correlation coefficientkorelační koeficient
Permutation testspermutační testy
Populationpopulace
powersíla
probabilitypravděpodobnost
probability density function (PDF)hustota pravděpodobnosti
probability distributionrozdělení pravděpodobnosti
probability theoryteorie pravděpodobnosti
random errorsnáhodné chyby
random samplenáhodný výběr
random variablenáhodná veličina
rankpořadí
Rank-based testspořadové testy
Ratiopoměrová
Regression sum of squaresregresní součet čtverců
residual sum of squaresreziduální součet čtverců
residualsrezidua
Samplevýběr
Sample correlation matrixvýběrová korelační matice
Sample covariancevýběrová kovariance
sample Kendall's rank correlation coefficientKendallův výběrový korelační koeficient
Sample kurtosisvýběrová špičatost
Sample meanvýběrový průměr
Sample Pearson correlationvýběrový korelační koeficient
Sample skewnessvýběrová šikmost
sample Spearman's rank correlation coefficientSpearmanův výběrový pořadový korelační koeficient
Sample standard deviationvýběrová směrodatná odchylka
Sample statisticsvýběrové statistiky
Sample variancevýběrový rozptyl
Sample variance-covariance matrixvýběrová kovarianční matice
sampling distributionvýběrové rozdělení
sign testznaménkový test
significance levelhladina významnosti
Simpson's paradoxSimpsonův paradox
Standard deviationsměrodatná odchylka
standard error (SE)střední chyba průměru
Statisticstatistika
Statistical inferencestatistická inference
Stochastic independencestochastická nezávislost
Tiesshodné hodnoty
total sum of squarescelkový součet čtverců
Two-way ANOVAdvoufaktorová analýza rozptylu / dvojné třídění
Variancerozptyl
Variance-covariance matrixkovarianční matice
within-groups (residual) sum of squaresreziduální
z-scorestandardizovaná hodnota