Probability — exam-style ME1 exercises with the spam filter: counting, tables, total probability and Bayes (and the row that should have been a column)
In the academy’s practice exam I gave 0.80 as the probability of spam given that the email has a link, and it was 0.26, because I divided by the row and not by the column. The number was correctly computed; what was wrong was the question it answered. That kind of mistake is not fixed with more calculations, but by reading the problem and saying out loud what the denominator is. This article is designed for that: problems like the ones in the continuous assessment, with the solution explained and what gets marked in each part.
It is the last article of the probability topic. Before it come the theory, the proofs and the R practice. If any part catches you out, go back to the right article: each exercise uses the same tools with new data.
Table of Contents
How to use this article
Probability is part of ME1’s EC1 (the first continuous assessment), together with descriptive statistics and random variables. In the real exam there is no standalone “Bayes exercise”: the probability parts sit inside an exercise with a context (a service, a machine, a variable), and one part usually needs the result of the previous one. That is why the exercises here are chained too.
- What the assessment is like. Four hours, in the classroom with your laptop, RStudio open and the exam browser. 50 points per assessment plus a bonus. It mixes hand calculations, a short proof and parts solved with R.
- Decimals. Results are given to 2 decimal places. Do the calculations with all of them and round at the end.
- The script. At the end you upload an
.Rfile with the code for each exercise; without it, that exercise is not marked. At the end of this article, in “For your script”, you have this topic’s functions ready to copy. - How to work. Read the whole exercise, try each part on paper or in RStudio and only then open the solution. The points for each part and the “How it is marked” notes are guidelines: they are mine, not the course’s, but they follow the way points are shared out in the exam.
Before computing any conditional probability, write the denominator in words: “of the emails with a link…”. It is the quickest way not to divide by the wrong thing.
Exercise 1: Monday’s inbox (10 points)
On Monday morning you have 20 unread emails. According to the filter, 5 are spam and 15 are legitimate, but you do not know which. You open 4 emails at random.
a) (2 points) In how many different ways can you choose the 4 emails you open, regardless of the order in which you open them?
b) (3 points) What is the probability that among the 4 there is exactly one spam? And at least one?
c) (2 points) 10 new emails arrive and the filter splits them into three folders: 5 to Primary, 3 to Promotions and 2 to Spam. How many different splits of the 10 (identified) emails are there with those sizes?
d) (3 points) A platform’s verification service sends 4-digit codes (from 0000 to 9999, all equally likely and independent). With R, compute the probability that among 100 emails with a code at least two have the same one, and the smallest number of emails for which that probability goes above 0.5.
Exercise 2: the server’s table (10 points)
The server’s weekly report classifies the 800 emails received by the folder the filter sent them to and by whether they contain a link:
| with link | no link | total | |
|---|---|---|---|
| Primary | 120 | 360 | 480 |
| Promotions | 150 | 50 | 200 |
| Spam | 96 | 24 | 120 |
| total | 366 | 434 | 800 |
An email from the week is picked at random. Let S = “is in Spam”, P = “is in Promotions” and L = “has a link”.
a) (2 points) Compute , and .
b) (3 points) Compute and . Explain in one sentence what each means in context and why they are so different.
c) (2 points) Are the events S and L independent? Justify your answer.
d) (3 points) Compute the probability that the email is in Promotions or has a link. Use that result to compute, without going back to the table, the probability that it is neither in Promotions nor has a link, and then check the result against the table.
Exercise 3: where does that spam come from? (15 points)
A student account receives emails from three places: 60 % from the ULPGC server, 25 % from Gmail accounts and 15 % from other servers. The proportion of spam is 1 % of what comes from ULPGC, 8 % of what comes from Gmail and 40 % of what comes from other servers.
a) (3 points) Compute the probability that an email picked at random is spam. Draw the tree.
b) (3 points) If an email is spam, what is the probability that it comes from each of the three places? Comment on the result by comparing it with the starting proportions.
c) (2 points) Check parts a) and b) with R by building the Bayes table (prior, likelihood, joint and posterior).
d) (4 points) The account has a filter that flags 95 % of the spam and, by mistake, 3 % of legitimate emails. Compute the probability that a flagged email is spam. If a second filter, which works independently of the first given the type of email, then also flags it (this one flags 85 % of the spam and 4 % of legitimate emails), what is the probability now that it is spam?
e) (3 points) Without assuming that the two filters are independent, prove that at least 80 % of the spam is flagged by both filters.
Bonus (2.5 points)
In an inbox where 25 % of the mail is spam, the person in charge wants a filter with sensitivity 0.90 that satisfies . What is the maximum proportion of legitimate emails it may flag by mistake? Solve it by rearranging and check it with uniroot() in R. Plot as a function of .
Solutions
Exercise 1
a) Choosing 4 emails out of 20 without order and without repetition are combinations:
Why combinations and not variations. Before the formula, the two usual questions. Does order matter? No: opening A and then B leaves you with the same four read emails as the other way round. Can anything repeat? No: you don’t open an email twice. The obvious route, , counts each group once for every order in which you could open it, and there are . That is why you divide by 24.
b) The 4845 groups from part a) are equally likely (you open at random), so Laplace applies. For exactly one spam: choose 1 spam out of 5 and 3 legitimate out of 15 (multiplication principle):
For at least one, by the complement (“none” = all 4 legitimate):
Why the complement. “At least one” is four cases: 1, 2, 3 or 4 spam. One by one you get groups and : the same, with four calculations instead of one. “None” is a single case.
“I first pick one spam and the other three from the 19 left”: , probability 1. The absurd result is the warning: a group with two spam is counted twice, once for each spam picked “first”.
c) Splitting 10 distinct objects into groups of 5, 3 and 2 is the multinomial coefficient:
Another way to see it: first choose the 5 for Primary (), then the 3 for Promotions among the 5 left (), and the last 2 go to Spam: .
Why not . The obvious idea is to give each email three possible folders: . But that counts every split, including all 10 in Spam, and the statement fixes the sizes. The multinomial starts from the orderings of the 10 emails and divides by the order inside each folder, which doesn’t matter.
Check you’ve got it: how many splits would there be with 4 emails in Primary, 4 in Promotions and 2 in Spam?
. You don’t divide by anything else because two folders hold 4: Primary and Promotions are different folders, and sending a group to one or the other gives different splits.
d) There are codes. As in the theory, by the complement: . With these numbers it cannot be computed as it is in R: is outside R’s range (you will see what happens in “What’s wrong here?”). We write it factor by factor, , which are numbers between 0 and 1:
collision <- function(n, N) 1 - prod((N - n + 1):N / N) # factor by factor: never overflows round(collision(100, N = 10000), 4) # P(some code repeated) with 100 emails p4 <- sapply(1:200, collision, N = 10000) # for n = 1, ..., 200 which(p4 > 0.5)[1] # first n with P > 0.5 round(p4[c(117, 118, 119, 120)], 4) # around the crossing
Output:
[1] 0.3914 [1] 119 [1] 0.4940 0.4999 0.5058 0.5117
With 100 emails, the probability of some repeated code is 0.39. You need 119 emails for it to go above 0.5: with 118 it is 0.4999 (still below) and with 119, 0.5058. Look at the last line: the crossing is very tight, which is why it is worth showing the values around it and not just the which.
How it is marked (guideline): a) 2 points for the number; 1 if the correct formula is used with an arithmetic slip. b) 1.5 + 1.5; for “at least one”, using the complement is valued. c) 1 for identifying the multinomial and 1 for the result. d) 1 for a correctly written function (that does not overflow), 1 for 0.39 and 1 for 119 with its check.
Exercise 2
a) With Laplace, dividing by the 800 emails:
b) Now the denominators differ. For the universe is the 366 emails with a link (the column); for , the 120 emails in Spam (the row):
In context: says that 80 % of the spam has a link; says that only 26 % of emails with a link are spam. They are so different because links are very common in all mail (in Primary and Promotions too): almost all spam has a link, but most emails with a link are not spam.
week <- matrix(c(120, 360, 150, 50, 96, 24), nrow = 3, byrow = TRUE,
dimnames = list(folder = c("primary", "promotions", "spam"),
link = c("with link", "no link")))
round(prop.table(week, margin = 2), 4) # P(folder | link): each column adds up to 1
round(prop.table(week, margin = 1), 4) # P(link | folder): each row adds up to 1
Output:
link
folder with link no link
primary 0.3279 0.8295
promotions 0.4098 0.1152
spam 0.2623 0.0553
link
folder with link no link
primary 0.25 0.75
promotions 0.75 0.25
spam 0.80 0.20
In the first table (margin = 2, conditional on the column) you read in the spam row, with link column. In the second (margin = 1, conditional on the row) you read in the same position. The same table cell, two different questions.
c) They are independent if . We compute:
They are not independent: knowing it has a link changes the probability of being in Spam (from 0.15 to 0.26). Put another way, .
One way to read the 0.0686. If they were independent, out of the 800 emails you would expect in Spam with a link, and the table has 96: almost twice as many.
Justifying it with “they have emails in common”. That says they are not mutually exclusive, which is something else. Independence means that knowing one doesn’t change the probability of the other.
d) By the union formula. We need , and :
For “neither Promotions nor link”, by De Morgan and the complement: .
Check against the table: “neither Promotions nor link” means the emails without a link in Primary and in Spam, , and . It matches.
Why go through the union. “Neither Promotions nor link” is what lies outside “Promotions or link”. The obvious move would be to multiply the complements, , but that assumes they are independent, and in this table they are not. De Morgan assumes nothing: that is why it gives the table’s 0.48.
How it is marked (guideline): a) 0.5 + 0.5 + 1. b) 1 + 1 for the numbers and 1 for the interpretation (without it, at most 2). c) 1 for the criterion and 1 for the conclusion. d) 1 for the union, 1 for De Morgan properly justified and 1 for the check.
Exercise 3
a) The three sources form a partition (an email comes from one place only and the three cover everything), so the law of total probability applies. We call the sources U, G and O:
The setup, before the calculation. Look at what the statement gives you: the spam within each source, …, not the other way round; those are the second-level branches of the tree. The obvious move would be to average the three percentages, , but then the ULPGC would weigh the same as “others”, and it sends four times as much mail. The total probability is that average, weighted by how much each source sends.
b) By Bayes, each tree branch over the total probability:
The three add up to 1 (0.0698 + 0.2326 + 0.6977 = 1.0001, because of rounding). Comment: the other servers send only 15 % of the mail but are the source of 70 % of the spam; ULPGC sends 60 % and only contributes 7 % of the spam. The data “is spam” has completely changed the picture: that is exactly what Bayes does.
Check you’ve got it: if an email is not spam, where is it most likely to come from?
From the ULPGC. It’s the same Bayes with the “legitimate” branches: , and , which add up to . Dividing: 0.65 for the ULPGC, 0.25 for Gmail and 0.10 for others. Knowing it is legitimate barely moves the starting split (0.60, 0.25, 0.15), because almost all mail is.
c)
bayes <- function(prior, likelihood) {
joint <- prior * likelihood
data.frame(prior = prior, likelihood = likelihood, joint = joint,
posterior = joint / sum(joint))
}
srv <- bayes(prior = c(ulpgc = 0.60, gmail = 0.25, others = 0.15),
likelihood = c(0.01, 0.08, 0.40))
round(srv, 4)
sum(srv$joint) # total probability of spam (part a)
Output:
prior likelihood joint posterior ulpgc 0.60 0.01 0.006 0.0698 gmail 0.25 0.08 0.020 0.2326 others 0.15 0.40 0.060 0.6977 [1] 0.086
The joint column holds the three tree branches (0.006, 0.020 and 0.060), their sum is 0.086 (part a) and the posterior column holds the three results of part b).
d) Now the “cause” is the type of email (spam or legitimate) and the “data” is that the filter flags it. The prior for spam is the total probability from part a), 0.086:
For the second filter, the prior is now the posterior from the first (0.7487 spam, 0.2513 legitimate), and since the filters are independent given the type of email, we just multiply by the second filter’s likelihood:
Why you can chain them. It is the same as a single Bayes with the data “both flag it”. Since they are independent given the type of email, and :
Independence is used exactly there, when you multiply the likelihoods. The common mistake is to stop at the numerator, : you still have to divide by everything the second filter flags, legitimate emails included.
f1 <- bayes(c(spam = 0.086, legitimate = 0.914), c(0.95, 0.03)) # first filter f2 <- bayes(setNames(f1$posterior, rownames(f1)), c(0.85, 0.04)) # second: the posterior becomes the prior round(f1, 4) round(f2, 4)
Output:
prior likelihood joint posterior
spam 0.086 0.95 0.0817 0.7487
legitimate 0.914 0.03 0.0274 0.2513
prior likelihood joint posterior
spam 0.7487 0.85 0.6364 0.9845
legitimate 0.2513 0.04 0.0101 0.0155
In context: with 8.6 % spam, a single “flagged” leaves a legitimate email in the spam folder one time in four (0.25); with both filters agreeing, the doubt drops to 1.6 %. Notice that the first filter, with sensitivity 0.95, gives “only” 0.75: the base rate again.
e) Call and the events “filter 1 flags it” and “filter 2 flags it”, and work with the probability conditional on spam, , which is a probability (proof 5 in the proofs article). By the union formula applied to Q:
Since Q is a probability, . Therefore:
This is Bonferroni’s inequality conditional on spam. We have not used independence: even if the filters failed on exactly the same emails, at least 80 % of the spam is flagged by both. (If they were independent, it would be , only slightly more.)
Why a bound and not a number. Without independence you can’t multiply: the filters could fail on the same emails or on different ones. What you always know is that a union can’t go above 1, and that gives a minimum; that is why the statement says “at least”. And you condition on spam because the 95 % and the 85 % are probabilities within spam.
Check you’ve got it: what does the same calculation say about the legitimate emails that both filters flag?
Nothing useful: , and you already knew a probability is greater than a negative number. The bound only says something when the two probabilities add up to more than 1.
How it is marked (guideline): a) 1 for identifying the partition, 1 for the tree and 1 for the result. b) 2 for the three probabilities and 1 for the comment. c) 2 with the table read correctly. d) 2 + 2. e) 1 for using that is a probability, 1 for the union and 1 for the bound; without justifying the conditioning step, at most 2.
Bonus
Rearranging. With sensitivity 0.90, 25 % spam and false alarm :
The filter may flag at most 1.58 % of legitimate emails.
The chain above, step by step. You solve it like an equation, watching the sign:
- Multiply by the denominator, which is positive, so the doesn’t flip: .
- Distribute the 0.95: .
- Subtract 0.21375: .
- Divide by 0.7125, also positive: .
Getting “less than or equal” makes sense: the more legitimate emails it flags, the bigger the denominator and the lower the probability. With it is already 0.91.
With R. uniroot() finds where a function equals 0 within an interval; we give it “the probability minus 0.95”:
g <- function(f) 0.9 * 0.25 / (0.9 * 0.25 + f * 0.75) - 0.95 # equals 0 at the f we want
r <- uniroot(g, interval = c(0.0001, 0.5))
round(r$root, 4)
curve(0.225 / (0.225 + 0.75 * x), from = 0, to = 0.1,
xlab = "false alarm f", ylab = "P(spam | flagged)")
abline(h = 0.95, lty = 2, col = "red")
Output:
[1] 0.0158
uniroot gives 0.0158, the same as rearranging. In the drawing (redrawn in the site colours) the curve goes down as grows and crosses the 0.95 line right at 0.0158: left of the point the filter meets the target; right of it, it does not. In the course’s exam, uniroot.all() from the rootSolve package is used, which returns every root in the interval; the site’s playground does not have it, but uniroot() (base R) gives the same root when there is only one.
How it is marked (guideline): 1 for setting it up, 0.75 for rearranging and 0.75 for the R check and the plot.
What’s wrong here?
Three solutions by classmates, each with one mistake. Read, try to spot it and then look at the explanation.
Snippet 1. For exercise 1 d), a classmate copies the function from the theory and calls it with 10,000 codes:
collision <- function(n, N) 1 - prod((N - n + 1):N) / N^n collision(100, N = 10000) collision(200, N = 10000)
Output:
[1] NaN [1] NaN
What is wrong. NaN means “Not a Number”: the calculation makes no numerical sense. is bigger than the largest number R can store (about ), so N^n is Inf; the product of the 100 numbers between 9901 and 10000 also goes to Inf; and Inf / Inf is NaN. The formula is right, but it cannot be computed this way. The fix is to divide factor by factor, prod((N - n + 1):N / N), which multiplies numbers below 1.
Trusting that “the formula is right” when R returns NaN, Inf or a suspicious 1. Look at how big the intermediate numbers get.
Snippet 2. For exercise 2 b), another classmate computes like this:
round(prop.table(week, margin = 1), 4)
Output:
link folder with link no link primary 0.25 0.75 promotions 0.75 0.25 spam 0.80 0.20
and answers ““, reading the spam row, with link column.
What is wrong. margin = 1 divides each cell by its row total: what you get is , “of the spam, how many have a link?”. For (“of those with a link, how many are spam?”) the denominator is the column: margin = 2, which gives 0.2623. It is my practice exam mistake.
After prop.table, look at what adds up to 1. If the rows add up to 1, you conditioned on the row; if the columns, on the column. The condition is what adds up to 1.
Snippet 3. For exercise 3 b), a classmate writes by hand:
P(others | spam) = P(spam | others) = 0.40 because "others" is the place with the most spam
What is wrong. She mixes up the likelihood and the posterior: she flips the conditional without applying Bayes. says what share of the mail from other servers is spam; says what share of the spam comes from other servers, and to go from one to the other you multiply by the prior (0.15) and divide by the total probability (0.086): . That the number looks similar here (0.40 against 0.70) does not mean it will in other problems; it can be very different.
Writing . It is only true if ; in general, Bayes.
Practice quiz
Before moving on to the next topic, check you have got it. This quiz is here to consolidate what this article explains: the ME1 exam is not a multiple-choice test (you solve problems by hand and with R), so no mark here counts. There are 10 questions on probability: key ideas, typical mistakes and many «what does this R code print?», with the outputs from really running it. In the short answers, a decimal point or a decimal comma both work. Answer without running anything, press Check and read the explanation for each option; you can repeat it as many times as you like.
For the probability that some code repeats among 100 chosen from 10,000, a classmate writes 1 - prod((N - n + 1):N) / N^n and R returns NaN. Why?
- 10000^100 is larger than the maximum R can store, so N^n and the product are Inf, and Inf / Inf is NaN
- The formula is wrong: it should be a sum
proddoes not accept vectors longer than 50roundis missing
Solution
Answer: 10000^100 is larger than the maximum R can store, so N^n and the product are Inf, and Inf / Inf is NaN
Trusting that «the formula is right» when R returns NaN, Inf or a suspicious 1 is the mistake. Check the size of the intermediate numbers: multiplying numbers below 1 does not overflow.
week is a table with the folder in the rows (inbox, promotions, spam) and whether it has a link in the columns. For P(spam | with link), what do you use?
prop.table(week, margin = 2)and read the spam row, with-link columnprop.table(week, margin = 1)prop.table(week)week["spam", "with link"] / sum(week)
Solution
Answer: prop.table(week, margin = 2) and read the spam row, with-link column
After prop.table, check what adds up to 1: if the rows do, you conditioned on the row; if the columns do, on the column. The condition is what adds up to 1.
Of the mail from other servers, 40 % is spam: P(spam | O) = 0.40. A classmate writes «P(O | spam) = 0.40». What is wrong?
- She flips the conditional without Bayes: to go from one to the other you multiply by the prior and divide by the total probability
- Nothing: P(A | B) and P(B | A) are always equal
- She should subtract: P(O | spam) = 1 − 0.40
- She should add the priors
Solution
Answer: She flips the conditional without Bayes: to go from one to the other you multiply by the prior and divide by the total probability
P(spam | O) says what share of the mail from other servers is spam (the likelihood); P(O | spam), what share of the spam comes from other servers (the posterior). To go from one to the other: Bayes.
What number does it print? (choose(n, r) gives the combinations of n elements taken r at a time.)
round(choose(5, 1) * choose(15, 3) / choose(20, 4), 2)
Solution
Answer: 0.47
It is the urn template: exactly 1 «good» one when drawing 4 from 20 with 5 good ones. Favourable cases C(5,1) · C(15,3) = 5 · 455 = 2275; possible C(20,4) = 4845; 2275 / 4845 = 0.47.
With the same urn (4 from 20, with 5 good ones), what is the probability of drawing at least one good one? (2 decimals.)
none <- choose(15, 4) / choose(20, 4) round(1 - none, 2)
Solution
Answer: 0.72
«At least one» is worked out through the complement: 1 − P(none) = 1 − C(15,4)/C(20,4) = 1 − 1365/4845 = 1 − 0.28 = 0.72. Adding the cases of 1, 2, 3 and 4 good ones would give the same, with more work.
Match each situation with its counting formula:
| Choose r of n, ordered, no repeats | |
| Choose r of n, ordered, with repeats | |
| Choose r of n, unordered, no repeats | |
| Split n into groups of sizes n1, n2… |
Definitions:
- n! / (n1! · n2! · …)
- n · r
- C(n, r) = n! / (r!(n − r)!)
- n! / (n − r)!
- n^r
Solution
- Choose r of n, ordered, no repeats → n! / (n − r)!
- Choose r of n, ordered, with repeats → n^r
- Choose r of n, unordered, no repeats → C(n, r) = n! / (r!(n − r)!)
- Split n into groups of sizes n1, n2… → n! / (n1! · n2! · …)
They are the cheat sheet’s permutations, permutations with repetition, combinations and multinomial. The key question is always: does order matter? Can it repeat?
A filter detects 95 % of spam and wrongly flags 3 % of normal mail. If 8.6 % of mail is spam, what is the probability that a flagged email is spam? (2 decimals.)
s <- 0.95; f <- 0.03; p <- 0.086 round(s * p / (s * p + f * (1 - p)), 2)
Solution
Answer: 0.75
Total probability of a flag: 0.95 · 0.086 + 0.03 · 0.914 = 0.0817 + 0.0274 = 0.1091. Bayes: 0.0817 / 0.1091 = 0.75. Although the filter is very accurate, one flag in four is normal mail, because spam is rare.
True or false?
- Two mutually exclusive events (which cannot happen together) are independent.
- If A and B are independent, so are the complement of A and B.
- P(A ∪ B) = P(A) + P(B) − P(A ∩ B).
- To apply total probability, the partition must add up to 1.
Solution
- F — Two mutually exclusive events (which cannot happen together) are independent.
- T — If A and B are independent, so are the complement of A and B.
- T — P(A ∪ B) = P(A) + P(B) − P(A ∩ B).
- T — To apply total probability, the partition must add up to 1.
Independent is not mutually exclusive: if A and B are exclusive and have positive probability, knowing A happened says B did not, so they depend on each other. In the union the intersection is subtracted so it is not counted twice.
Two filters in a row: the first leaves the probability of spam at 0.75. What is used as the prior of the second filter?
- 0.75, the posterior of the first
- 0.086, the original prior
- 0.5, because nothing is known
- The product 0.086 · 0.75
Solution
Answer: 0.75, the posterior of the first
In R: the posterior from bayes() in the first step is the prior of the second (step2 <- bayes(step1$posterior, lik2)).
What does it print?
factorial(10) / (factorial(5) * factorial(3) * factorial(2))
Solution
Answer: 2520
It is the multinomial: ways of splitting 10 elements into groups of 5, 3 and 2. 3,628,800 / (120 · 6 · 2) = 3,628,800 / 1440 = 2520.
Try it in the R playground
Open the site’s R playground and solve the whole of exercise 3 with this script; then change the server percentages and watch everything move.
bayes <- function(prior, likelihood) {
joint <- prior * likelihood
data.frame(prior, likelihood, joint, posterior = joint / sum(joint))
}
srv <- bayes(c(ulpgc = 0.60, gmail = 0.25, others = 0.15), c(0.01, 0.08, 0.40))
srv
p_spam <- sum(srv$joint)
f1 <- bayes(c(spam = p_spam, legitimate = 1 - p_spam), c(0.95, 0.03))
f2 <- bayes(setNames(f1$posterior, rownames(f1)), c(0.85, 0.04))
round(f2$posterior, 4)
What to look at:
- The
srvtable in the console: check thatposterioradds up to 1. - In Environment,
p_spammust be 0.086. - Change the likelihood of “others” to 0.20: how much does drop?
- Set the first filter’s sensitivity to 0.99 and see how much the final posterior changes.
Cheat sheet: probability
The essentials in 30 seconds. A probability is always “within something”: changes the universe to B. For “at least one”, the complement. For several paths, total probability; to flip a conditional, Bayes. Independent is not mutually exclusive.
Results
- · · if , .
- .
- .
- De Morgan: , .
- Bonferroni: . Boole: .
- Ordered without repetition: · with repetition · permutations .
- Combinations: · with repetition · multinomial .
- · Pascal · .
- Conditional: · product .
- Total: · Bayes: .
- Independence: ; if A and B are, so are and , and , and .
- Series / parallel with independent failures : the series fails with ; the parallel with .
| I want… | Code | Result (example) |
|---|---|---|
| Combinations | choose(20, 4) | 4845 |
| Ordered selections | prod(10:7) | 5040 |
| Multinomial | factorial(10) / (factorial(5) * factorial(3) * factorial(2)) | 2520 |
| Joint probabilities of a table | prop.table(t) | everything adds up to 1 |
| Conditional on the column | prop.table(t, margin = 2) | each column adds up to 1 |
| Conditional on the row | prop.table(t, margin = 1) | each row adds up to 1 |
| Bayes with a partition | bayes(prior, likelihood) | posterior column |
| Estimate a probability by simulation | mean(replicate(10000, …)) | a proportion |
| Solve | uniroot(g, c(a, b))$root | the root |
Templates from the exercises
- Exactly k “good” when picking r from an urn with K good and N − K bad: (exercise 1 b: 0.47).
- At least one: (exercise 1 b: 0.72).
- Some repeat among n with N values: (with N = 10000, 119 to go above 0.5).
- Two filters: the first’s posterior is the second’s prior (exercise 3 d: 0.75 → 0.98).
| Symptom | Likely cause |
|---|---|
| A probability above 1 | You are adding overlapping events without subtracting the intersection |
NaN or Inf in a counting calculation | Huge powers or factorials: divide factor by factor |
| The conditional comes out as 0.80 and “should” be small | You divided by the row instead of the column (or the other way round) |
The posterior column does not add up to 1 | You did not divide by the sum of the joint |
| You get the sensitivity as Bayes’ answer | You confused and |
Before handing in, ask yourself
- Have I written in words what the denominator of each conditional is?
- Are the events I am adding disjoint, or do I need to subtract the intersection?
- Does my partition add up to 1, and so does the
posteriorcolumn? - Have I rounded to 2 decimal places only at the end?
For your script
The topic’s code in my own commented version, to copy into the exam’s .R file. They are functions that work for any exercise of this kind; none of them includes problem statements.
# ===== Topic 2: probability =====
# Counting
ordered <- function(n, r) prod((n - r + 1):n) # without repetition, with order
ordered_rep <- function(n, r) n^r # with repetition, with order
comb_rep <- function(n, r) choose(n + r - 1, r) # no order, with repetition
multinomial <- function(n, groups) factorial(n) / prod(factorial(groups)) # groups = c(n1, n2, ...)
# Probability of "exactly k good" when drawing r from an urn (without replacement)
urn <- function(k, r, good, total) choose(good, k) * choose(total - good, r - k) / choose(total, r)
# Some value repeated among n, with N equally likely values (does not overflow)
collision <- function(n, N) 1 - prod((N - n + 1):N / N)
first_n <- function(N, threshold = 0.5) { # smallest n with P(repeated) > threshold
n <- 1
while (collision(n, N) <= threshold) n <- n + 1
n
}
# Contingency tables: t is a matrix with named rows and columns
joints <- function(t) prop.table(t) # P(row and column)
given_column <- function(t) prop.table(t, margin = 2) # P(row | column)
given_row <- function(t) prop.table(t, margin = 1) # P(column | row)
independent <- function(t, row, col) { # compares P(A and B) with P(A)P(B)
p <- prop.table(t)
c(joint = p[row, col], product = sum(p[row, ]) * sum(p[, col]))
}
# Total probability and Bayes with a partition
bayes <- function(prior, likelihood) {
joint <- prior * likelihood
data.frame(prior = prior, likelihood = likelihood, joint = joint,
posterior = joint / sum(joint))
}
# Update in two steps: the first's posterior is the second's prior
# step2 <- bayes(setNames(step1$posterior, rownames(step1)), likelihood2)
# A test or filter with sensitivity s, false alarm f and prevalence p
p_positive <- function(s, f, p) s * p + f * (1 - p)
p_cause_given_pos <- function(s, f, p) s * p / p_positive(s, f, p)
# Simulate to check (relative frequency)
estimate <- function(experiment, times = 10000) mean(replicate(times, experiment()))
# example: estimate(function() any(duplicated(sample(1:1000, 38, replace = TRUE))))
Quick check that they all work (the outputs match those in the exercises):
c(ordered(10, 4), multinomial(10, c(5, 3, 2)), round(urn(1, 4, 5, 20), 4)) first_n(10000) round(p_cause_given_pos(0.95, 0.03, 0.086), 4)
Output:
[1] 5040.0000 2520.0000 0.4696 [1] 119 [1] 0.7487
What comes next?
With this topic you have the tools to talk about what has not happened yet. In ME1’s topic 3, discrete random variables, chance becomes a number: how many spam emails arrive in an hour, how many emails you open until you find a legitimate one… That is where the probability mass function, the expected value, the variance and the first models (binomial, Poisson, geometric) appear. The conditional probability and independence from this topic are the foundation of all of them.
If you want to revise first, go back to the theory, the proofs or the R practice, and if something is still unclear, ask Leo, who has read the article.
Keep goingAll Statistics articlesDid this article help you? Here is how you can support SergioLearns →
Ready for the exam?ME1 EC1 mock exam — the 4-hour exam with R alongside, four versions, a mark out of 50 and every solution with its code (and why the .R counts too)


