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 zeroHow 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.
| Part | Points | What it is |
|---|---|---|
| Report 1 and report 2 | 10 + 10 | At the beginning of two seminars. Details at least two weeks before. |
| Final practical assignment | 20 | At the last seminar, 100 minutes. Tidyverse only: no basic R syntax or basic R graphics. |
| Needed to reach the exam | 20 of 40 | Below 20 points, you get result X and cannot take the exam. |
| Final exam | 60 | In 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
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.
| Word | Meaning | Diet example |
|---|---|---|
| Population populace | Everybody or everything you care about | all people who could follow this diet |
| Sample výběr | The part you really measured | the 24 people on diet A |
| Parameter parametr | A true number about the population. Fixed, but unknown. | the true mean weight loss |
| Statistic statistika | A number calculated from the sample. Known, but it changes from sample to sample. | kg, the sample mean |
| Estimate odhad | A 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 measures | True 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.
| Symbol | Read it as | Example |
|---|---|---|
| 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, variance | topic Random variables | |
| null hypothesis, alternative hypothesis | topic 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" |
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.
| Measure | What it is | On 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 |
| Mode | The most frequent value | none here, because each value appears once |
Why have two measures of the centre? Suppose somebody mistypes 66 as 166.
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.
Build it step by step on a tiny sample, with mean 5:
| deviation | squared | |
|---|---|---|
| 2 | −3 | 9 |
| 4 | −1 | 1 |
| 4 | −1 | 1 |
| 5 | 0 | 0 |
| 10 | +5 | 25 |
| sum | 0 | 36 |
- Find each deviation from the mean.
- Square them. The plain deviations always add up to 0, so their average tells you nothing. Squares are never negative.
- Add the squares. This is the sum of squares, here 36. ANOVA is built on this quantity.
- Divide by This gives the variance:
- Take the square root. This gives the 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.
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.
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.553201If 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.
- 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.
quantile(x)
0% 25% 50% 75% 100%
45.00 50.25 54.00 57.50 66.00
IQR(x)
[1] 7.25A 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:
Symmetric: mean = median
Long right tail: mean above median
Long left tail: mean below median
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.
| Rule | Formula | Example with a die |
|---|---|---|
| Opposite (complement) | ||
| Or, for events that cannot happen together | ||
| And, for independent events | two 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.
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
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
Heads in 10 fair coin flips
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
- 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.
- 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
The second number in is the variance. In R, functions take the standard deviation: pnorm(x, 3, 2).
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:
is the standard normal distribution. So a question about any normal variable becomes a question about a single curve.
Heights: from a value to a probability
Heights follow What share of people are taller than 185 cm?
- Convert to a z-score:
- Find the area to the left of it is 0.933.
- We want the right side: about 6.7 %.
1 - pnorm(185, mean = 170, sd = 10)
[1] 0.0668072Heights: 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.
qnorm(0.90, mean = 170, sd = 10)
[1] 182.8155R 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.
| Function | Question it answers | Example |
|---|---|---|
pnorm | probability: what is the area to the left of this value? | pnorm(1.96) gives 0.975 |
qnorm | quantile: which value has this area to its left? | qnorm(0.975) gives 1.96 |
dnorm | density: how high is the curve here? | dnorm(0) gives 0.399 |
rnorm | random: draw random values | rnorm(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.
| Middle area | Each tail | Quantile | Value |
|---|---|---|---|
| 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.
The standard error (SE) střední chyba průměru is the standard deviation of the sample mean:
| Standard deviation, | Standard error, | |
|---|---|---|
| Describes | how much people differ from each other | how much your guess of the mean would change in a new sample |
| With more data | stays about the same | gets smaller |
| One-minute data | 6.55 seconds | seconds |
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.
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
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.
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?
| Property | Meaning | Picture |
|---|---|---|
| Unbiased | On average over many samples, it hits the true value: | Arrows centred on the target |
| Low variance | It changes little from sample to sample. | Arrows close together |
| Consistent | It 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
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.
| Sample | mean | divide by | divide by |
|---|---|---|---|
| 1, 1 | 1.0 | 0.0 | 0.00 |
| 1, 2 | 1.5 | 0.5 | 0.25 |
| 1, 3 | 2.0 | 2.0 | 1.00 |
| 2, 1 | 1.5 | 0.5 | 0.25 |
| 2, 2 | 2.0 | 0.0 | 0.00 |
| 2, 3 | 2.5 | 0.5 | 0.25 |
| 3, 1 | 2.0 | 2.0 | 1.00 |
| 3, 2 | 2.5 | 0.5 | 0.25 |
| 3, 3 | 3.0 | 0.0 | 0.00 |
| average of 9 | 2.0 | 0.667 | 0.333 |
The average of the sample means is 2, exactly Dividing by gives on average, exactly Dividing by gives which is too small.
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.
- 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 %.
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:
- The sample mean is normal around the true mean, with standard deviation So after standardizing:
- 95 % of the standard normal lies between ±1.96:
- Multiply everything by
- Rearrange to get alone in the middle:
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
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.
| df | 2 | 4 | 9 | 19 | 30 | 75 | 100 | 1000 | normal |
|---|---|---|---|---|---|---|---|---|---|
| 4.303 | 2.776 | 2.262 | 2.093 | 2.042 | 1.992 | 1.984 | 1.962 | 1.960 |
Assumption: a random sample from a normal distribution, or a large enough sample for the central limit theorem to work.
The whole calculation by hand, on the one-minute data
- Estimate:
- Standard deviation:
- Standard error:
- Critical value: df, and 95 % confidence means
- Margin of error:
- Interval: which gives seconds.
qt(0.975, df = 9)
[1] 2.262157
t.test(x)$conf.int
[1] 49.81212 59.18788
attr(,"conf.level")
[1] 0.95In 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.
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." | OK | The usual short way to say it. "Confident" refers to the method. |
| "This method catches the true mean in 95 % of samples." | Correct | The 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." | Wrong | The 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." | Wrong | The 95 % is about catching not about where the next mean lands. |
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.
| Change | Effect on the interval | Why |
|---|---|---|
| Larger sample | narrower | is in the denominator, and gets smaller too |
| Less variable data | narrower | is in the numerator. Better measurements help. |
| Higher confidence level | wider | To be more sure of catching the fish, you need a bigger net |
| One-minute data | interval | width | |
|---|---|---|---|
| 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.
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):
Where R's numbers for the diets come from
In Lecture 1, R reports the interval without explaining it. Now we can rebuild it.
- Estimate: kg.
- Standard error:
- Critical value:
- Margin of error:
- Interval: which gives ✓
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
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
Two overlapping intervals do not prove that two groups are the same. To compare two groups, look at the interval for their difference.
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.
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.
| Parameter | Interval | Distribution | Where in the course |
|---|---|---|---|
| mean | above | ||
| difference | Lecture 1 | ||
| group mean in ANOVA | Lecture 2 | ||
| pair of groups, Tukey | studentized range | Lecture 2 | |
| proportion | or an exact method | normal, or binomial | Lecture 3 |
| variance | below | ||
| correlation | through Fisher's then transform back | normal | Lecture 5 |
| regression coefficient | Lecture 6 |
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.
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.
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.
| Court | Statistical test |
|---|---|
| Presumed innocent | the null hypothesis: no effect |
| What the prosecutor claims | the alternative hypothesis: there is an effect |
| Evidence | The test statistic calculated from the data |
| "Beyond reasonable doubt" | The significance level usually 0.05 |
| Guilty | Reject |
| Not guilty. This does not mean proved innocent! | Do not reject This does not mean that is true! |
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,
- Assume is true. Then the number of heads follows
- How likely is a result this extreme or more?
- Count the other side too. 0 or 1 heads would be just as extreme, since is two-sided. So
- Decide. so reject . There is enough evidence that the coin is not fair.
binom.test(9, 10, p = 0.5)$p.value
[1] 0.02148438That 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?
A value near 0 agrees with A large value, positive or negative, speaks against
One-sample t-test: did people guess 60 seconds on average?
against at
- Statistic: The mean is 2.65 standard errors below 60.
- Distribution under
- p-value: the area beyond ±2.654 is
- Decision: so reject People tend to guess too early.
| Way to decide | Check | Result |
|---|---|---|
| p-value | reject | |
| critical value | reject | |
| confidence interval | reject |
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.
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." | Correct | This is the definition. |
| "There is a 3 % chance that is true." | Wrong | That would be Conditions cannot be swapped. |
| "There is a 97 % chance that is true." | Wrong | Same mistake. |
| "The effect is large." | Wrong | A small p-value can come from a tiny effect and a huge sample. |
| " is true." | Wrong | We 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
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| Line | Meaning |
|---|---|
t = -2.6541 | The test statistic The mean is 2.65 standard errors below 60. |
df = 9 | Degrees of freedom, It tells you that |
p-value = 0.0263 | Below 0.05, so reject |
alternative hypothesis | What was. Always check that this is what you meant. "Not equal" means two-sided. |
95 percent confidence interval | The CI for the mean. The value 60 is outside it, so reject. |
mean of x | The estimate |
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(μ, σ²)
Student t(d)
Chi-squared χ²(d)
Fisher F(d₁, d₂)
Binomial Bin(n, p)
Exponential Ex(λ)
| Distribution | What it describes | Where you use it | R name |
|---|---|---|---|
| Normal | Measurements, errors, and means of large samples | everywhere | norm |
| Student | Normal, divided by an estimate of its SD | means, differences, regression coefficients | t |
| Chi-squared | A sum of squares of standard normals. Never negative. | variances, goodness of fit, Kruskal-Wallis | chisq |
| Fisher | A ratio of two variances. Never negative. | ANOVA, overall test of regression | f |
| Binomial | Number of successes in tries | sign test, goodness of fit | binom |
| Poisson | Number of rare events in a fixed time | goodness of fit | pois |
| Exponential | Waiting times | goodness of fit | exp |
| Uniform | All values equally likely | random numbers | unif |
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.
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 theory | Mathematical statistics | Machine / statistical learning | |
|---|---|---|---|
| Starts from | definitions and axioms | a sample of real data | a large amount of real data |
| Does | gives definitions, theorems and proofs for working with random events | collects, organizes, analyzes, interprets and presents data; fits models, estimates parameters, tests hypotheses | finds patterns and makes predictions, often with heuristic methods |
| Says how precise it is? | no real data here | yes, always | usually 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
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
| Kind | What it does | Typical tools |
|---|---|---|
| Descriptive statistics popisná statistika | Summarizes 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 dat | Looks at the data, usually with pictures. | frequency plot, boxplot, histogram, scatter plot, QQ plot |
| Statistical inference statistická inference | Says 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.
| Family | Assumption | Examples | Trade-off |
|---|---|---|---|
| Parametric | The 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 analysis | Easy to compute and explain, but with strict assumptions |
| Nonparametric | Very few assumptions. No specific distribution is needed. | rank statistics and rank tests, nonparametric ANOVA, rank correlations, functional data analysis | Usable almost everywhere, but often less power |
| Semiparametric | A mix of both. | Cox proportional hazards model in survival analysis | Not 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.
| Level | Allowed operations | Type | In R | Examples |
|---|---|---|---|---|
| Nominal nominální | belongs to a set | categorical, discrete | factor | blood type, gender, region |
| Ordinal ordinální | also order: sorting. Distances have no meaning. | categorical, discrete | ordered factor | highest education, grades, competition ranking |
| Interval intervalová | also distance: Ratios have no meaning because zero is not fixed. | numeric, typically continuous | numeric, integer | temperature in °C, calendar year |
| Ratio poměrová | also Zero and scale are fixed. | numeric, typically continuous | numeric, integer | temperature 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 |> or %>% makes code read like a sentence.
| Library | Job | Library | Job |
|---|---|---|---|
dplyr | manipulate data: filter, sort, group, summarize | tibble | modern data frames |
tidyr | reshape and tidy | stringr | strings |
ggplot2 | graphics (grammar of graphics) | forcats | categorical variables (factors) |
readr | fast import of CSV, TSV and so on | lubridate | dates and times |
purrr | functional 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 to | Use |
|---|---|
| create or load a table | data.frame, tibble, expand_grid, read.* |
| change or add columns | mutate, mutate(across), transmute, rename |
| choose columns | select, pull |
| choose rows | filter, slice |
| sort rows | arrange |
| split into subtables | group_by |
| calculate summaries | summarise, summarise(across) |
| switch wide and long format | pivot_longer, pivot_wider |
| join two tables | left_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.
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"))
)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
data |>
group_by(Diet) |>
summarise(size = n(), mean = mean(WeightLoss), st.dev = sd(WeightLoss),
variance = var(WeightLoss), median = median(WeightLoss))| Diet | size | mean | st.dev | variance | median |
|---|---|---|---|---|---|
| A | 24 | 3.30 | 2.24 | 5.02 | 3.05 |
| B | 27 | 3.03 | 2.52 | 6.37 | 3.30 |
| C | 27 | 5.15 | 2.40 | 5.74 | 5.40 |
Diet C looks better: about 2 kg more. Is that a real effect or just luck? Tests answer this question.
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.
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:
| Discrete | Continuous | |
|---|---|---|
| Values | at most countably many points on the line | uncountably many values, an interval |
| Used for | categorical and numerical data | typically numerical data |
| Names | Bernoulli (alternative), binomial, geometric, hypergeometric, Poisson, negative binomial | continuous 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.
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
Subtract the mean, divide by the standard deviation. The result is the standard normal distribution, with mean 0 and variance 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.
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.
Step 2. In practice we do not know Replace it with its unbiased estimator, the sample mean
Why
The sample mean is itself a random variable, because it comes from the random sample. It also creates one constraint:
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
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:
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
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
CDF F(x): the same area, read as a height
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.
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.
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)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.
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 decision | Truth: is true | Truth: 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 |
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
- State and from the research question.
- Check the assumptions about the data and choose a test, with a test statistic whose distribution under is known.
- Choose typically
- Calculate the observed value of the statistic.
- Calculate the p-value
- If reject in favor of
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:
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
Shapiro-Wilk normality test on the diets
the sample follows a normal distribution. it does not.
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.37204003All 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:
- Set up the critical region
- 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
| Alternative | Critical 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:
- Calculate the confidence interval (CI) for matching
- 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.
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.
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 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 R | t.test(..., var.equal = TRUE) | t.test(...), the default |
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
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:
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.148148Unfortunately 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
| Way | Reading | Decision |
|---|---|---|
| p-value | reject | |
| Confidence interval | Parameter: 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 |
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).
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.676642Unrealistic one: The boxplots already show that A is not higher.
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.676642Why 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
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.
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 | |
|---|---|---|
| 2 | 1 | 0.05 |
| 3 | 3 | 0.14 |
| 4 | 6 | 0.26 |
| 5 | 10 | 0.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
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.
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
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:
| group | observations | size | sample mean | assumed 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:
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 observations are mutually independent.
- Random errors follow the normal distribution,
- 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:
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.
Three tables, same data
Read each table and connect them.
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.
- Split a deviation by adding and subtracting
- Replace unknown means with their estimators:
- Square both sides and sum over all observations, using
- The mixed term disappears:
- What remains is the theorem.
| Name | Measures | Meaning |
|---|---|---|
| total sum of squares celkový součet čtverců | observations around the overall mean | all the variability. It is the sample variance without dividing by |
| between-groups sum of squares regresní | group means around the overall mean | variability explained by factor |
| within-groups (residual) sum of squares reziduální | observations around their own group mean | variability 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
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.
| Sum | Calculation | Result | df | SS / df |
|---|---|---|---|---|
| between | each person counts their group's distance: | 78 | 2 | 39 |
| within | inside each group: | 6 | 6 | 1 |
| total | all nine around 5: | 84 | 8 |
The degrees of freedom are and Check: and ✓ Then The critical value is so reject , and R agrees:
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 1The 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
Rule for degrees of freedom: count the values, then subtract 1 for each average you had to estimate.
| Sum | Values used | Constraints | df | Distribution |
|---|---|---|---|---|
| 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
Under If we reject at level
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.
| source | df | sum of squares | mean squares | statistic | p |
|---|---|---|---|---|---|
| factor | |||||
| Residuals | |||||
| Total |
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.74Read 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.
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.
| df | Sum Sq | Mean Sq | F | p | |
|---|---|---|---|---|---|
| Dataset 1: A | 2 | 353.8 | 176.91 | 189.6 | <2e-16 |
| Dataset 1: Residuals | 42 | 39.2 | 0.93 | ||
| Dataset 2: A | 2 | 0.7 | 0.35 | 0.037 | 0.963 |
| Dataset 2: Residuals | 42 | 392.3 | 9.34 |
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
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.
95 % CI for diet A
so which gives kg.
| Diet | mean | margin | 95 % CI (kg) | |
|---|---|---|---|---|
| A | 24 | 3.300 | 0.974 | (2.33; 4.27) |
| B | 27 | 3.026 | 0.918 | (2.11; 3.94) |
| C | 27 | 5.148 | 0.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
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.
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
| Method | Idea | When 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. |
"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).
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.
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.
Table of pairwise comparisons
Use group = FALSE to get the differences, p-values and confidence intervals.
| Contrast | difference | Bonferroni p | Tukey p | Scheffé p | Decision |
|---|---|---|---|---|---|
| A − B | 0.274 | 1.0000 | 0.9125 | 0.9203 | no difference |
| A − C | −1.848 | 0.0224 | 0.0201 | 0.0272 | different |
| B − C | −2.122 | 0.0051 | 0.0048 | 0.0070 | different |
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:
- Fit the ANOVA model.
- Calculate residuals rezidua
- Check normality of the residuals. If it looks suspicious, also check within each group.
- 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
| Normality | Homogeneity of variance | |
|---|---|---|
| Tests | Shapiro-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. |
| Graphs | Q-Q plot | boxplots, residuals vs. fitted values |
| If violated | The 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 do | Kruskal-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
Assumptions for the diets
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
75All p-values are above 0.05. We do not reject normality or equal variances, so the ANOVA result can be used.
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
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).
| supp | dose | size | mean | st.dev | lowest | Q1 | median | Q3 | highest |
|---|---|---|---|---|---|---|---|---|---|
| OJ | 0.5 | 10 | 13.2 | 4.46 | 8.2 | 9.7 | 12.2 | 16.2 | 21.5 |
| OJ | 1 | 10 | 22.7 | 3.91 | 14.5 | 20.3 | 23.5 | 25.6 | 27.3 |
| OJ | 2 | 10 | 26.1 | 2.66 | 22.4 | 24.6 | 26.0 | 27.1 | 30.9 |
| VC | 0.5 | 10 | 7.98 | 2.75 | 4.2 | 5.95 | 7.15 | 10.9 | 11.5 |
| VC | 1 | 10 | 16.8 | 2.52 | 13.6 | 15.3 | 16.5 | 17.3 | 22.5 |
| VC | 2 | 10 | 26.1 | 4.80 | 18.5 | 23.4 | 26.0 | 28.8 | 33.9 |
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:
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
Interaction: the gap changes
Sums of squares, balanced design
Fisher (1925) derived the model for the balanced design, where every cell has the same size
| Sum | Formula | follows |
|---|---|---|
Each row of the table has its own which follows an F distribution under its own null hypothesis.
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.2df check:
The order of testing matters
- Test the interaction first: all against some Look at and
- If rejected: the impact of varies across the levels of Evaluating main effects can be misleading. Examine simple main effects.
- If not rejected: test and interpret main effects. that is all that is all
Means, effects and coefficients
| Means (grand mean 18.81) | dose 0.5 | dose 1 | dose 2 | supp mean |
|---|---|---|---|---|
| OJ | 13.23 | 22.70 | 26.06 | 20.663 |
| VC | 7.98 | 16.77 | 26.14 | 16.963 |
| dose mean | 10.605 | 19.735 | 26.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.
| Combination | mean | Tukey | Scheffé |
|---|---|---|---|
| VC:2 | 26.14 | a | a |
| OJ:2 | 26.06 | a | a |
| OJ:1 | 22.70 | a | a |
| VC:1 | 16.77 | b | b |
| OJ:0.5 | 13.23 | b | bc |
| VC:0.5 | 7.98 | c | c |
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.
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)$groupsThe 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
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
54All p-values are above 0.05, so normality and homogeneity are not rejected.
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.
| Type | Compares models | Note |
|---|---|---|
| I, sequential | Y~A; then Y~A Y~A+B; then Y~A+B Y~A+B+A:B | Depends on the order of the factors. is unadjusted for |
| II, hierarchical | Y~A Y~A+B and Y~B Y~A+B; then Y~A+B Y~A+B+A:B | Independent of the order |
| III, partial | Y~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:B | Independent of the order |
Testing: first the interaction.
| Interaction significant | Interaction not significant | |
|---|---|---|
| Type I | Do not interpret main effects, examine simple effects. | is adjusted for but is unadjusted for |
| Type II | Do 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. |
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 54These 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.
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 methods | Nonparametric methods | |
|---|---|---|
| Assumption | A strict family of distributions, for example | No parametric assumption. Only general ones, for example "continuous" or "symmetric". |
| Work with | Point and interval estimates and tests of the parameters | Ranks or rearrangements of the sample |
| Data | Only data that fit the assumption | A 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:
Order statistics are neither independent nor identically distributed. You only sorted the numbers, but you lost both properties of a random sample.
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.
| Method | Formula | Idea |
|---|---|---|
| Average ranks (mid-ranks) | Give all tied values the average of their positions | |
| Standard competition | All tied values get the best position. Two golds, then bronze. | |
| Modified competition | All tied values get the worst position | |
| Dense ranking | Ranks only for unique values, with no gaps | |
| Random ranking | Ties are broken at random |
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
order(X) # ordering permutation
sort(X) # ordered sample, same as X[order(X)]
rank(X) # ranks
rank(X, ties.method = "average")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
- Calculate the differences
- Count the positive ones:
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.
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
Sign test on the one-minute data
| 53 | 48 | 45 | 55 | 63 | 51 | 66 | 56 | 50 | 58 | |
| −7 | −12 | −15 | −5 | +3 | −9 | +6 | −4 | −10 | −2 |
and Since is not rejected.
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.2Where 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" | Uses | p-value | Decision at 5 % |
|---|---|---|---|
| Sign test | only above or below | 0.1094 | do not reject |
| Wilcoxon signed-rank | direction and rank of the size | 0.0371 | reject |
| One-sample t-test | the values themselves, and assumes normality | 0.0263 | reject |
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.
For a larger sample, the binomial looks more and more normal. This is why works:
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
Calculate then run the one-sample test on
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
- Calculate the differences
- Sort them by absolute value:
- is the rank of in this sequence.
- Calculate or the rank sums and
Rank the absolute values, and give the sign back afterwards. The lecturer says that students often forget this.
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:
Wilcoxon on the one-minute data
| 1 | 53 | −7 | 6 | −1 |
| 2 | 48 | −12 | 9 | −1 |
| 3 | 45 | −15 | 10 | −1 |
| 4 | 55 | −5 | 4 | −1 |
| 5 | 63 | +3 | 2 | +1 |
| 6 | 51 | −9 | 7 | −1 |
| 7 | 66 | +6 | 5 | +1 |
| 8 | 56 | −4 | 3 | −1 |
| 9 | 50 | −10 | 8 | −1 |
| 10 | 58 | −2 | 1 | −1 |
- and So
- and
- Since we reject .
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 60R reports as V. Its p-value is below 0.05, so we reject too. The sign test on the same data could not reject.
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
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
| Version | Note | ||
|---|---|---|---|
| Mann-Whitney, for numeric data | or | the original, stochastic order | |
| General | identical: | different: | consistent only when |
| Strict, for numeric data | identical: | 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
- Join both samples:
- Sort the combined sample:
- are the ranks of the values, and the ranks of the values, in the combined sample.
- Calculate the rank sums and
- Calculate and
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).
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:
| (sorted) | 4.2 | 4.3 | 4.4 | 4.5 | 5.0 | 5.1 | 5.2 | 5.4 | 5.5 | 5.6 | 5.7 | 5.8 | 5.9 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| rank | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| group | B | A | B | B | B | A | A | B | A | A | A | A | A |
- with with
- Check: ✓
- Since is rejected.
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 0R reports as W.
The t-test sees the yields
The rank test sees only the positions
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
- Join all observations.
- Sort them: with
- is the (mid)rank of in the combined sample.
- Calculate the sum of ranks in each group:
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
Potato varieties
The total weight of potatoes from one plant was measured for four varieties. Compare the location shift across varieties.
| Variety | weights | ranks | ||
|---|---|---|---|---|
| 1 | 0.9, 0.8, 0.6, 0.9 | 3.5, 2, 1, 3.5 | 4 | 10 |
| 2 | 1.3, 1.0, 1.3 | 11, 5.5, 11 | 3 | 27.5 |
| 3 | 1.3, 1.5, 1.6, 1.1, 1.5 | 11, 13.5, 15, 7.5, 13.5 | 5 | 60.5 |
| 4 | 1.1, 1.2, 1.0 | 7.5, 9, 5.5 | 3 | 22 |
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.
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 cThe "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
Under If reject at asymptotic level
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 cthe 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
Under If reject at asymptotic level
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 data | statistic | p-value | Decision at 5 % |
|---|---|---|---|
| Kruskal-Wallis | 10.68 | 0.0136 | reject |
| Van der Waerden | 10.51 | 0.0147 | reject |
| Median test | 6.43 | 0.0925 | do 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.
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
- Choose a statistic that measures the effect.
- Create the distribution of under from its values under all rearrangements of the original sample.
- Calculate the observed value
- A value of in the extremes suggests a significant effect against
- Calculate the p-value according to or or
| Advantages | Limitations |
|---|---|
|
|
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
- Select a statistic of interest, for example
- Calculate the observed value
- Let be the combined sample: first values from last from
- Let
- There are ways to split elements into subsets of sizes and
- Under each has probability
- Find all of them and calculate for each.
- The one-sided p-value is
When there are too many rearrangements, resample without replacement times, with large, usually
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.
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?
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.
The lecturer warned about the Seeing Theory page: its CDF uses the other definition, This course uses
Some widely used distributions
| Discrete | Absolutely continuous |
|---|---|
| Bernoulli (alternative), binomial, multinomial, hypergeometric, Poisson, geometric, negative binomial, discrete uniform | Gaussian (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). | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| number of families with this many boys | 3 | 10 | 22 | 31 | 14 | 4 |
| 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 clients | 14 | 16 | 10 | 9 | 8 | 5 | 3 | 5 |
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.
| category | sum | ||||
|---|---|---|---|---|---|
| observed frequencies | |||||
| expected probabilities | 1 | ||||
| expected frequencies |
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í,
- Each with and
- are not mutually independent.
- They are negatively correlated:
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
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
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.
| Face | 1 | 2 | 3 | 4 | 5 | 6 | sum |
|---|---|---|---|---|---|---|---|
| Observed | 5 | 8 | 9 | 8 | 10 | 20 | 60 |
| Expected | 10 | 10 | 10 | 10 | 10 | 10 | 60 |
| 2.5 | 0.4 | 0.1 | 0.4 | 0 | 10 | 13.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.
chisq.test(c(5, 8, 9, 8, 10, 20))
X-squared = 13.4, df = 5, p-value = 0.019914.6When parameters are unknown
If is only a family with unknown parameters the modified minimum method estimates them by solving:
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
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
- Categories are all possible outcomes under
- Estimate unknown parameters ( of them), if necessary.
- Observed frequencies:
- Expected frequencies: using the PMF under
- Check the assumptions, and merge suitable adjacent categories if necessary.
- Calculate compare with and decide.
Example 1: are the numbers of boys Bin(5, 0.5)?
| 0 | 3 | 0.0312 | 2.62 | 0.054 |
| 1 | 10 | 0.156 | 13.1 | 0.744 |
| 2 | 22 | 0.312 | 26.2 | 0.688 |
| 3 | 31 | 0.312 | 26.2 | 0.860 |
| 4 | 14 | 0.156 | 13.1 | 0.058 |
| 5 | 4 | 0.0312 | 2.62 | 0.720 |
| sum | 84 | 1 | 84 |
Always check the sums first: df is not rejected.
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.6809R warns because two are below 5. Merge adjacent categories: 0-1 and 4-5.
| 0-1 | 13 | 0.187 | 15.7 |
| 2 | 22 | 0.312 | 26.2 |
| 3 | 31 | 0.312 | 26.2 |
| 4-5 | 18 | 0.187 | 15.7 |
chisq.test(tab2$N.j, p = tab2$p.j)
X-squared = 2.3492, df = 3, p-value = 0.5032A 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
- Categories are disjoint intervals covering all possible outcomes under
- Estimate unknown parameters ( of them), if necessary.
- Observed frequencies:
- Expected frequencies: using the CDF under
- Check the assumptions, and merge adjacent categories if necessary.
- 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 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.5 | 14 | 0.286 | 20.0 |
| (3;6] | 4.5 | 16 | 0.204 | 14.3 |
| (6;9] | 7.5 | 10 | 0.146 | 10.2 |
| (9;12] | 10.5 | 9 | 0.104 | 7.29 |
| (12;15] | 13.5 | 8 | 0.0744 | 5.21 |
| (15;18] | 16.5 | 5 | 0.0531 | 3.72 |
| (18;21] | 19.5 | 3 | 0.0379 | 2.66 |
| (21;∞) | ∞ | 5 | 0.0948 | 6.64 |
| sum | 70 | 1 | 70 |
df because we estimated one parameter. is not rejected. The data do not contradict the exponential distribution.
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.
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.
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
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.
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 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
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-sidedis not rejected. The biggest vertical gap is about 0.08. By hand, gives the critical value and is below it.
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
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.
| Test | Based on | In 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 statistics | shapiro.test |
| Cramér-von Mises (Cramér 1928; von Mises 1928) | distance between CDFs | nortest::cvm.test |
| Anderson-Darling (1952) | distance between CDFs | nortest::ad.test |
| Lilliefors (1967; Dallal and Wilkinson 1986) | like Kolmogorov-Smirnov | nortest::lillie.test |
| Pearson's chi-squared (1900) | frequencies | nortest::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
For a sample from a Gaussian distribution, as So a Gaussian sample has and
Three distributions with the same mean
| distribution | skewness | kurtosis | mean | median | mode |
|---|---|---|---|---|---|
| lognormal LN(1, 1.1) | 8.34 | 190.42 | 5 | 2.72 | 0.80 |
| normal N(5, 4) | 0 | 0 | 5 | 5 | 5 |
| Weibull Wb(10, 5.2) | −0.64 | 0.59 | 5 | 5.11 | 5.24 |
- Symmetric: mean ≈ median ≈ mode.
- Positive skew: mean > median > mode.
- Negative skew: mean < median < mode.
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.
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
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.
Anderson-Darling: reject if
Cramér-von Mises: reject if
Lilliefors test
the sample follows with unknown parameters. non-Gaussian.
- Estimate:
- 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.
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 3 continued: is the average restart time normal?
| Test | statistic | p-value |
|---|---|---|
| D'Agostino skewness | skew = 1.6741, z = 8.0167 | 1.086e-15 |
| Anscombe-Glynn kurtosis | kurt = 8.4030, z = 6.0808 | 1.196e-09 |
| Jarque-Bera | JB = 414.14 | < 2.2e-16 |
| Shapiro-Wilk | W = 0.88816 | 1.653e-12 |
| Cramér-von Mises | W = 0.67469 | 9.46e-08 |
| Anderson-Darling | A = 4.3807 | 6.651e-11 |
| Lilliefors | D = 0.11366 | 3.601e-08 |
| Pearson chi-square | P = 49.041 | 3.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.
Lecture 5 · 13 October 2026
Correlation analysis
How do you measure and test the relationship between two or more variables?
You will need: variance, Greek and Latin letters, how a test works and confidence intervals.
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.
| Probability | Statistics |
|---|---|
| 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.
| Probability | Statistics |
|---|---|
| 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 |
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.
Covariance and correlation by hand
Five pairs, with
| product | ||||
|---|---|---|---|---|
| 1 | 2 | −2 | −1 | 2 |
| 2 | 1 | −1 | −2 | 2 |
| 3 | 4 | 0 | 1 | 0 |
| 4 | 3 | 1 | 0 | 0 |
| 5 | 5 | 2 | 2 | 4 |
| sum | 0 | 0 | 8 |
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.2 | very weak or no association |
| 0.2 – 0.4 | weak association |
| 0.4 – 0.6 | moderate association |
| 0.6 – 0.8 | strong association |
| 0.8 – 1.0 | very 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.
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
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.testuses 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.
r = 0.5 with n = 27
- Transform
- Standard error on the scale:
- Interval on the scale: which gives
- 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.
The five points from above: r = 0.8 with n = 5
with Since we do not reject even though looks strong.
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.8The 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
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
- 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.
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.
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).
| species | r | p |
|---|---|---|
| Adelie | 0.391 | 1.0e-06 |
| Chinstrap | 0.654 | 0.0e+00 |
| Gentoo | 0.643 | 0.0e+00 |
| all together | −0.235 | 1.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
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).
| Members | Income | Expense |
|---|---|---|
| 4 | 100 | 35 |
| 2 | 80 | 30 |
| 4 | 120 | 40 |
| 1 | 30 | 10 |
| 5 | 150 | 60 |
| 3 | 120 | 45 |
| 4 | 130 | 50 |
dat |> ggplot(aes(x = Members, y = Expense)) +
geom_point(size = 3.5) +
stat_ellipse(level = 0.95, type = "norm", segments = 100)
dat |> GGally::ggpairs()Test the correlation of members and expenses
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.8896204and 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)
Fisher z statistic under H₀: N(0, 1)
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 | |
|---|---|---|
| Contains | sample covariances of all pairs | sample correlations of all pairs |
| Shape | square symmetric, positive definite | square symmetric |
| Diagonal | sample 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 statistic | function | |
|---|---|---|
| sample mean | mean(X) | |
| sample variance | var(X) | |
| sample standard deviation | sd(X) | |
| sample covariance | cov(X, Y) | |
| sample correlation | cor(X, Y) | |
| correlation test | cor.test(X, Y) | |
| sample variance-covariance matrix | cov(Z) | |
| sample correlation matrix | cor(Z) | |
| scatterplots | GGally::ggpairs | |
| correlogram | GGally::ggcorr, ggcorrplot::ggcorrplot |
The matrices for Example 1
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.000Check: ✓
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.
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.
5.8Spearman's rank correlation
What if the data are ordinal or not bivariate normal? Calculate Pearson's correlation on the ranks.
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").
against meaning and are pořadově korelované rank-correlated.
- Under If reject
- Under If reject at asymptotic level
Spearman for Example 1
| 35 | 30 | 40 | 10 | 60 | 45 | 50 | |
| 4 | 2 | 4 | 1 | 5 | 3 | 4 | |
| 100 | 80 | 120 | 30 | 150 | 120 | 130 | |
| = rank of | 3 | 2 | 4 | 1 | 7 | 5 | 6 |
| = rank of | 5 | 2 | 5 | 1 | 7 | 3 | 5 |
| = rank of | 3 | 2 | 4.5 | 1 | 7 | 4.5 | 6 |
Three households have 4 members, at positions 4, 5, 6, so each gets average rank 5. Then
# 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
| Members | Income | Expense | |
|---|---|---|---|
| Members | 1 | 0.92 | 0.89 |
| Income | 0.92 | 1 | 0.99 |
| Expense | 0.89 | 0.99 | 1 |
Spearman
| Members | Income | Expense | |
|---|---|---|---|
| Members | 1 | 0.86 | 0.82 |
| Income | 0.86 | 1 | 0.99 |
| Expense | 0.82 | 0.99 | 1 |
Pearson
| Age | Memory | IQ | Reading | |
|---|---|---|---|---|
| Age | 1 | 0.72 | 0.85 | |
| Memory | 0.72 | 1 | 0.82 | |
| IQ | 1 | |||
| Reading | 0.85 | 0.82 | 1 |
Spearman
| Age | Memory | IQ | Reading | |
|---|---|---|---|---|
| Age | 1 | 0.78 | 0.88 | |
| Memory | 0.78 | 1 | 0.8 | |
| IQ | 1 | |||
| Reading | 0.88 | 0.8 | 1 |
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.
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.
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
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
# 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| Coefficient | Works on | Measures | Use for | Example 1 | p |
|---|---|---|---|---|---|
| Pearson | values | linear association | interval/ratio data, bivariate normal | 0.890 | 0.0073 |
| Spearman | ranks | monotonic (rank) association | ordinal or non-Gaussian | 0.815 | 0.0254 |
| Kendall | pairs, order only | ordinal association | ordinal, comparing rankings | 0.720 | 0.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.
| Coefficient | Question | Notation |
|---|---|---|
| Pearson | between and ignoring | |
| Partial | between and excluding the effect of | |
| Multiple | between and the set |
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
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_inv <- solve(cor(Z))
D <- sqrt(diag(R_inv))
R_part <- -R_inv / outer(D, D)
diag(R_part) <- 1The test
against For a sample of size from an -dimensional normal distribution, with the sample partial correlation, under If reject p-value:
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) <- 0It 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
Pearson against partial correlations
Pearson
| Members | Income | Expense | |
|---|---|---|---|
| Members | 1 | 0.92 | 0.89 |
| Income | 0.92 | 1 | 0.99 |
| Expense | 0.89 | 0.99 | 1 |
Partial
| Members | Income | Expense | |
|---|---|---|---|
| Members | 1 | ||
| Income | 1 | 0.94 | |
| Expense | 0.94 | 1 |
Pearson
| Age | Memory | IQ | Reading | |
|---|---|---|---|---|
| Age | 1 | 0.72 | 0.85 | |
| Memory | 0.72 | 1 | 0.82 | |
| IQ | 1 | |||
| Reading | 0.85 | 0.82 | 1 |
Partial
| Age | Memory | IQ | Reading | |
|---|---|---|---|---|
| Age | 1 | -0.69 | 0.69 | |
| Memory | 1 | 0.48 | ||
| IQ | -0.69 | 0.48 | 1 | |
| Reading | 0.69 | 1 |
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.
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
| Pearson | partial | Insight |
|---|---|---|
| strong | strong | True independent relationship. |
| strong | not significant | Spurious or mediated: a fake relationship, driven by a shared confounder, or fully mediated by other variable(s). |
| not significant | strong | Suppressed: a true underlying relationship masked or cancelled by other variable(s). |
| strong | strong, opposite direction | Simpson'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
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 <- 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
against For a sample of size from an -dimensional normal distribution, under If reject p-value:
Example 2: IQ against the other three variables
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.7310867The 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?
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
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.
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
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 regression | Multiple regression | |
|---|---|---|
| Studies | a 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:
- 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
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:
odhad metodou nejmenších čtverců
The residual sum of squares reziduální součet čtverců is the lowest achievable value of
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
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.
is the best unbiased estimator of with the lowest variance. And
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.
- and are independent.
Test of overall regression (omnibus)
against there exists with
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
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.
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
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,
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 output | How to read it |
|---|---|
Estimate | Fitted function: One extra cm adds 0.23 kg on average. |
t value | Estimate / Std. Error: |
Pr(>|t|) | p-value of Both coefficients are significant. |
Residual standard error | estimated standard deviation of random errors. df |
Multiple R-squared | The model explains 19.26 % of the variability. |
F-statistic | The overall test: the model is significant. |
Inspect the design matrix.
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.6The first column of ones belongs to and the second holds the heights.
Estimates and intervals.
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.0004203521Check: 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.
6.6Confidence and prediction intervals
Let be a response for predictor values Let
| Confidence interval | Prediction interval predikční interval | |
|---|---|---|
| For | the expected value the regression function at | a future observation at |
| Formula | ||
| Includes | variability of LS estimates only | variability 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.
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.
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
| Calculation | Result | Question it answers | |
|---|---|---|---|
| CI | What is the average expense of all households with income 100? | ||
| PI | What will the expense of one new household with income 100 be? |
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
Sex is a factor. In the model it becomes a dummy variable: 1 for male, 0 for female. Now we fit 2 parallel lines.
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.
The design matrix with a dummy.
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 0Check 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.
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.
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-16The 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.
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.
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-16The 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.
6.9Coefficient of determination
- 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.
- 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).
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?
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.3519Adding 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
| model | R² | adj. R² | logLik | AIC |
|---|---|---|---|---|
| m1 | 0.193 | 0.191 | −1625 | 3256 |
| m2 | 0.563 | 0.561 | −1463 | 2933 |
| m3 | 0.563 | 0.561 | −1463 | 2935 |
| m4 | 0.564 | 0.561 | −1462 | 2934 |
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.
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.0005855Fitted 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.
6.12Correlation coefficients through regression
Regression explains all the correlations from Lecture 5.
Pearson correlation and R-squared
is the association between and is the share of variability of explained by from lm(Z1 ~ 1 + Z2).
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).
Generally, the multiple correlation is the Pearson correlation between and its best linear approximation by
# 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.9878276Partial correlation and R-squared
Take the variability of that could not explain (the denominator). What share of it does explain in addition (the numerator)?
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
# 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.3007187The 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.
| Question | Data | Parametric test | Nonparametric test |
|---|---|---|---|
| How precise is my estimate? | any | a confidence interval for that parameter. Most test functions in R report one. | |
| Is the mean or median equal to a given value? | one sample | one-sample t-test t.test | symmetric: Wilcoxon signed-rank wilcox.testskewed: sign test binom.test |
| Did something change, before and after? | two paired samples | paired t-test (t-test on differences) | paired Wilcoxon or sign test on the differences |
| Do two groups differ? | two independent samples | two-sample t-test, Welch | Mann-Whitney wilcox.test, permutation test |
| Do 3+ groups differ? | one factor | one-way ANOVA aov, then Tukeyunequal variances: Welch's ANOVA oneway.test | Kruskal-Wallis agricolae::kruskal, then Mann-Whitney with Bonferronimany outliers: median test |
| Effects of two factors? | two factors | two-way ANOVA aov(y ~ A * B) | |
| Do data follow a given distribution? | one sample | any, grouped: Pearson χ² continuous and fully specified: Kolmogorov-Smirnov ks.test | |
| Are the data normal? | one sample | Shapiro-Wilk shapiro.test, Lilliefors nortest::lillie.test. Not K-S with estimated parameters! | |
| Do two samples have the same distribution? | two samples | two-sample K-S, or Mann-Whitney in its general form | |
| Are variances equal? | groups | Bartlett bartlett.test, only with normal data | Levene car::leveneTest |
| Are two variables related? | two numeric variables | Pearson cor.test | Spearman, Kendall (method =) |
| Related, removing the effect of others? | 3+ variables | partial correlation | |
| Predict from | numeric | linear regression lm | |
How to write a test result
- State and in words and symbols.
- Say which test, and why its assumptions hold. Fix first.
- Report the statistic, df and p-value.
- Decide: " so we reject " or " so we do not reject ". Never " is true".
- Write the conclusion in plain language about the real question.
- Look at a plot, and check that the result makes sense.
Formula sheet
| Topic | Formula |
|---|---|
| Sample variance, SD | |
| Standard error of a mean | estimated by |
| Any test statistic | |
| Any confidence interval | estimate 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.
| Topic | In the material | Used 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 plot | drawn with df 51.86 (the lecturer said so) | df 48.86 |
| ANOVA notation | group 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 example | one title has | as in the analysis |
| Kolmogorov-Smirnov | next to an approximation that fits itself | |
| Cramér-von Mises | ||
| History of correlation | Karl Pearson (1985) | 1895 |
| Partial correlation | twice | second is |
| Multivariate normal | mixes 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.
| English | Czech |
|---|---|
| alternative hypothesis | alternativní hypotéza |
| analysis of variance (ANOVA) | analýza rozptylu |
| between-groups sum of squares | regresní |
| central limit theorems | centrální limitní věta |
| coefficient of multiple correlation | koeficient mnohonásobné korelace |
| coefficient of partial correlation | koeficient parciální korelace |
| confidence interval | interval spolehlivosti |
| confidence interval (CI) | interval spolehlivosti |
| Covariance | kovariance |
| critical region | kritická oblast |
| cumulative distribution function | distribuční funkce |
| Descriptive statistics | popisná statistika |
| design matrix | matice plánu |
| effect | efekt |
| empirical CDF (ECDF) | empirická distribuční funkce |
| Estimate | odhad |
| estimator | odhad |
| exchangeability | zaměnitelnost |
| Expected (theoretical) frequencies | teoretické četnosti |
| expected value | střední hodnota |
| Expected value (mean) | střední hodnota |
| Exploratory data analysis (EDA) | exploratorní analýza dat |
| Fitted values | vyrovnané hodnoty |
| grand mean | celkový průměr |
| group mean | skupinový průměr |
| Homogeneity of variance | homogenita rozptylu |
| interaction effect | interakce |
| Interval | intervalová |
| least-squares (LS) method | metoda nejmenších čtverců |
| linear contrast | kontrast |
| machine / statistical learning | strojové / statistické učení |
| main effect | hlavní efekt |
| mathematical statistics | matematická statistika |
| mode | mód |
| multinomial distribution | multinomické rozdělení |
| Nominal | nominální |
| normal distribution | normální rozdělení |
| null hypothesis | nulová hypotéza |
| Observed (empirical) frequencies | empirické četnosti |
| one-way ANOVA | jednofaktorová analýza rozptylu / jednoduché třídění |
| order statistic | pořádková statistika |
| ordered sample | uspořádaný výběr |
| Ordinal | ordinální |
| outliers | odlehlé hodnoty |
| p-value | p-hodnota |
| Parameter | parametr |
| Pearson correlation coefficient | korelační koeficient |
| Permutation tests | permutační testy |
| Population | populace |
| power | síla |
| probability | pravděpodobnost |
| probability density function (PDF) | hustota pravděpodobnosti |
| probability distribution | rozdělení pravděpodobnosti |
| probability theory | teorie pravděpodobnosti |
| random errors | náhodné chyby |
| random sample | náhodný výběr |
| random variable | náhodná veličina |
| rank | pořadí |
| Rank-based tests | pořadové testy |
| Ratio | poměrová |
| Regression sum of squares | regresní součet čtverců |
| residual sum of squares | reziduální součet čtverců |
| residuals | rezidua |
| Sample | výběr |
| Sample correlation matrix | výběrová korelační matice |
| Sample covariance | výběrová kovariance |
| sample Kendall's rank correlation coefficient | Kendallův výběrový korelační koeficient |
| Sample kurtosis | výběrová špičatost |
| Sample mean | výběrový průměr |
| Sample Pearson correlation | výběrový korelační koeficient |
| Sample skewness | výběrová šikmost |
| sample Spearman's rank correlation coefficient | Spearmanův výběrový pořadový korelační koeficient |
| Sample standard deviation | výběrová směrodatná odchylka |
| Sample statistics | výběrové statistiky |
| Sample variance | výběrový rozptyl |
| Sample variance-covariance matrix | výběrová kovarianční matice |
| sampling distribution | výběrové rozdělení |
| sign test | znaménkový test |
| significance level | hladina významnosti |
| Simpson's paradox | Simpsonův paradox |
| Standard deviation | směrodatná odchylka |
| standard error (SE) | střední chyba průměru |
| Statistic | statistika |
| Statistical inference | statistická inference |
| Stochastic independence | stochastická nezávislost |
| Ties | shodné hodnoty |
| total sum of squares | celkový součet čtverců |
| Two-way ANOVA | dvoufaktorová analýza rozptylu / dvojné třídění |
| Variance | rozptyl |
| Variance-covariance matrix | kovarianční matice |
| within-groups (residual) sum of squares | reziduální |
| z-score | standardizovaná hodnota |