Probability — R practice with the spam filter: simulate a week, count repeated codes and Bayes in a table (and the prob I wrote backwards)
The first time I simulated an inbox with sample(), three out of four emails came out as spam, and it took me a while to see that the order of prob is what counts. I had written sample(c("spam", "legitimate"), …, prob = c(0.75, 0.25)) thinking “75 % legitimate”, but R gives each probability to the element in the same position: 0.75 to the first one, which was “spam”. The code raised no error at all; it just produced an impossible inbox. Since then, after every simulation I check the proportion with mean() before believing anything.
This is the practice for the probability topic. In the theory you saw the ideas with the ULPGC email spam filter, and in the proofs, why they are true. Here we put them to work in three medium-level programs, like the course’s lab sessions: simulate a week of email to see the frequency approach the probability (and estimate Bayes by counting), count when a verification code repeats and what happens when the numbers are too big, and build Bayes in a table with a function of our own that works for any exercise. The data are made up but look like real data: spam proportions that are not round, filters that fail and codes that repeat.
Table of Contents
Before you start
Make sure you are clear about:
- What a conditional probability is and how to compute it from a table: .
- The law of total probability and Bayes’ theorem, with the tree from the theory.
- The formulas for ordered selections and combinations, and their R versions:
prod(),choose(),factorial(). - That the relative frequency over many repetitions approaches the probability.
If any of these sounds shaky, go over the theory before moving on.
Every program starts with set.seed(2026). The seed fixes R’s sequence of “random” numbers: that way you get exactly the same outputs as here. If you remove it, each run gives slightly different numbers, which is also instructive. The programs work the same in RStudio and in the site’s R playground.
Program 1: a simulated week of the filter
The server receives emails and 25 % are spam. The filter flags 90 % of the spam and, by mistake, 2 % of legitimate emails. We want to simulate 5000 emails and see three things: how the proportion of spam gets closer to 0.25 as emails arrive, how many the filter flags, and what proportion of the flagged emails really is spam, to compare it with the 0.9375 given by Bayes. The catch: the filter’s result depends on whether the email is spam, so it cannot be simulated with a single sample().
The idea
We do it in the same order as the tree in the theory:
- For each email, we first decide whether it is spam: a random number between 0 and 1 (
runif) below 0.25. - The cumulative proportion after each email is “spam seen so far over emails seen so far”:
cumsum()divided by1, 2, …, n. - Then we decide whether the filter flags it, with the probability of its branch: 0.90 if it is spam, 0.02 if not. That is
ifelse(). - To estimate we keep only the flagged emails and look at what proportion is spam: conditioning is filtering.
Before coding, think of the tree: what is decided first and what depends on what? The code has to follow the same order as the branches.
Before running anything, work out what you expect. If the tree’s probabilities came true to the letter, out of 5000 emails 1250 would be spam and 3750 legitimate, and each group would split according to its branch:
| Tree branch | Calculation | Expected | Why |
|---|---|---|---|
| spam and flagged | 1125 | the filter catches 90 % of the spam | |
| spam not flagged | 125 | the 10 % that slips past it | |
| legitimate flagged | 75 | the false alarms | |
| legitimate not flagged | 3675 | what it gets right with legitimate emails |
The table the simulation produces won’t give these exact numbers, but it has to look like them. If you get 3000 flagged spam emails, the bug is in the code, not in the randomness. And notice that Bayes already comes out of this without a formula: of the flagged emails you expect, 1125 are spam, and .
The code
set.seed(2026)
n <- 5000 # emails in the simulated week
is_spam <- runif(n) < 0.25 # TRUE with probability 0.25: the email is spam
prop <- cumsum(is_spam) / seq_len(n) # proportion of spam after each email (cumsum counts the TRUEs)
round(prop[c(10, 100, 1000, 5000)], 4) # the proportion after 10, 100, 1000 and 5000 emails
max(which(abs(prop - 0.25) > 0.02)) # last email at which it was more than 0.02 away from 0.25
plot(prop, type = "l", ylim = c(0, 0.5),
xlab = "Emails received", ylab = "Proportion of spam")
abline(h = 0.25, lty = 2, col = "red") # the true probability
# the filter: each email uses the probability of its branch of the tree
flagged <- ifelse(is_spam, runif(n) < 0.90, runif(n) < 0.02)
table(spam = is_spam, flagged = flagged) # the week's 2 x 2 table
round(mean(is_spam[flagged]), 4) # estimated P(spam | flagged): spam among the flagged
round(mean(flagged), 4) # estimated P(flagged)
Output
[1] 0.2000 0.2700 0.2560 0.2504
[1] 455
flagged
spam FALSE TRUE
FALSE 3662 86
TRUE 138 1114
[1] 0.9283
[1] 0.24
How to read it
Output by output, since each one tells you something:
0.2000 0.2700 0.2560 0.2504: the proportion of spam after 10, 100, 1000 and 5000 emails. With 10 emails, 2 spam, 20 %; with 5000, 25.04 %, four ten-thousandths from the probability. That is the law of large numbers in numbers.455: the last email at which the proportion was more than 0.02 away from 0.25. From email 456 onwards, it always stays between 0.23 and 0.27. It is the dotted vertical line in the drawing.- The plot (redrawn in the site colours; in RStudio it is black with the red line): in the first emails the line jumps from 0 to 0.4, because a single email changes a proportion of few a lot; then it sticks to the dashed 0.25 line and stays there. That is what relative frequency approaching probability looks like.
- The table crosses what is true (rows,
spam) with what the filter did (columns,flagged). The four cells: 3662 legitimate not flagged (right), 86 legitimate flagged (false alarms), 138 spam not flagged (got through) and 1114 spam flagged (right). Check the totals: 3662 + 86 + 138 + 1114 = 5000. 0.9283: of the flagged, 1114 are spam: . Bayes gave 0.9375. They are close, but not equal: it is an estimate from 1200 flagged emails, with its sampling error.0.24: the proportion flagged, , exactly the total probability from the theory (). This time it matched to the hundredth; with another seed it would be close, not exact.
In context: in a week of 5000 emails, the filter would send 86 legitimate ones to spam. If one of them is the room-change email, now you know why it is worth checking the spam folder before an exam.
The first ten emails, one by one
The prop line does in one go what by hand is this table. With set.seed(2026), the first ten numbers from runif(n) are these (you can see them with round(runif(10), 4) right after the seed):
| runif | Below 0.25? | cumsum | prop | Why | |
|---|---|---|---|---|---|
| 1 | 0.6987 | No | 0 | 0 | no spam has arrived yet |
| 2 | 0.5565 | No | 0 | 0 | 0 out of 2 |
| 3 | 0.1401 | Yes | 1 | 0.3333 | the first spam: 1 out of 3 |
| 4 | 0.2857 | No | 1 | 0.25 | just misses: 1 out of 4 |
| 5 | 0.5554 | No | 1 | 0.2 | 1 out of 5 |
| 6 | 0.0251 | Yes | 2 | 0.3333 | 2 out of 6: a single email raises the proportion by 13 points |
| 7 | 0.4662 | No | 2 | 0.2857 | 2 out of 7 |
| 8 | 0.8610 | No | 2 | 0.25 | 2 out of 8 |
| 9 | 0.2525 | No | 2 | 0.2222 | misses by 0.0025: “below” is strict |
| 10 | 0.5808 | No | 2 | 0.2 | 2 out of 10, the 0.2000 in the output |
Look at how much each email moves things. The sixth one raises the proportion from 0.2 to 0.3333, because it is 1 out of 6. At email 5000, one more spam would move it by at most . That is why the plot jumps around at the start and stays still at the end: it isn’t that randomness calms down, it’s that each new email weighs less in the proportion.
Check you’ve got it: if email 11 were spam, what would prop[11] be?
cumsum would go from 2 to 3, because one more TRUE is added, and seq_len(n) would be 11 at that position. So prop[11] would be . With 11 emails, one spam raises the proportion by more than 7 points; with 5000, you wouldn’t even notice.
Questions you might ask
Why runif(n) < 0.25 and not sample()? They give the same: a uniform number between 0 and 1 is below 0.25 with probability 0.25. We use runif because it returns TRUE/FALSE directly, and logicals are very easy to count: sum() counts the TRUEs and mean() gives their proportion.
What exactly does cumsum(is_spam) / seq_len(n) do? cumsum keeps adding: after email , how many spam there have been so far. seq_len(n) is the vector 1, 2, …, n. Dividing element by element, position holds “spam up to / “: the cumulative proportion.
Why ifelse(is_spam, runif(n) < 0.90, runif(n) < 0.02)? Because the filter is not the same for every email: it depends on the branch. ifelse looks at each email and, if it is spam, uses the draw with 0.90; if not, the one with 0.02. It is a way of writing a tree in one line. Careful: it generates both whole vectors and picks, so it uses random numbers.
Why is is_spam[flagged] a conditional probability? Because is_spam[flagged] keeps only the flagged emails, and mean() gives the proportion of spam within them. Conditioning on “flagged” means keeping the flagged ones: the same as the table column in the theory.
Why is it not exactly 0.9375? Because 0.9375 is the probability and 0.9283 is a proportion in a sample of 1200 flagged emails. With more emails (try n <- 500000) the estimate gets closer; whatever difference remains is chance.
Writing prob = c(0.75, 0.25) in sample(c("spam", "legitimate"), …) thinking 0.75 is for “legitimate”. R pairs them by position: the first probability goes with the first element. After simulating, always check with mean() or table() that the proportion is the one you wanted.
What if the filter raised more false alarms: 10 % of legitimate emails instead of 2 %?
Before running it: the spam doesn’t change, so the spam row should stay the same. What grows is the cell of flagged legitimate emails, and with it has to drop.
set.seed(2026) n <- 5000 is_spam <- runif(n) < 0.25 # the same week as in program 1 flagged <- ifelse(is_spam, runif(n) < 0.90, runif(n) < 0.10) # 10 % false alarm instead of 2 % table(spam = is_spam, flagged = flagged) round(mean(is_spam[flagged]), 4) # estimated P(spam | flagged) round(0.90 * 0.25 / (0.90 * 0.25 + 0.10 * 0.75), 4) # the Bayes value, to compare
Output:
flagged spam FALSE TRUE FALSE 3343 405 TRUE 138 1114 [1] 0.7334 [1] 0.75
The spam row is identical (138 and 1114): with the same seed you get the same random numbers, and only the threshold for legitimate emails has changed. Flagged legitimate emails go from 86 to 405 (about were expected) and the estimate drops from 0.9283 to 0.7334, close to the 0.75 from Bayes. 2 % or 10 % looks like a small difference, but since there are three legitimate emails for every spam, each point of false alarm weighs three times as much: now one in four flagged emails is legitimate.
Try it yourself
- Change the spam rate to 0.05 and estimate again. Compare it with the 0.7031 that Bayes gives in the theory.
- Plot the cumulative proportion of
is_spam[flagged](the Bayes estimate as flagged emails arrive) and addabline(h = 0.9375).
Program 2: when does a verification code repeat?
A service sends a 3-digit code (1000 possible) in each email. We want the probability that, among emails, at least two carry the same code, for from 1 to 80; to find from which it goes above 0.5; to check it by simulation; and to plot the curve. The catch: the formula involves huge products and powers, and we must make sure R does not overflow.
The idea
- By the complement: , and “all different” is ordered selections without repetition over ordered selections with repetition (the theory explains it).
- We write the formula as a function of and apply it to 1, 2, …, 80 with
sapply(). which(p > 0.5)[1]gives the first above 0.5.- To simulate: we draw 38 random codes with replacement and check whether there are duplicates (
any(duplicated(...))); we repeat 10,000 times withreplicate(), and the proportion ofTRUEestimates the probability.
Before coding, think about how big the numbers get: . R copes up to about ; with 1000 codes and 80 emails it fits, but what about 10,000 codes and 200 emails?
All different, email by email
The formula makes more sense if you build it email by email. The first code can be anything. The second has to avoid one of the 1000: it has 999 good ones left. The third has to avoid two: it has 998 left. Each new email has it a little harder, and the probabilities multiply because each code is drawn on its own:
| Emails (n) | New factor | P(all different) | P(some repeated) | Why |
|---|---|---|---|---|
| 1 | 1 | 0 | with a single code there’s nothing to clash with | |
| 2 | 0.999 | 0.001 | the second has to avoid 1 code | |
| 3 | 0.997002 | 0.002998 | it avoids 2: | |
| 4 | 0.994011 | 0.005989 | it avoids 3 | |
| 5 | 0.990035 | 0.009965 | it avoids 4 |
Multiplying the factors in the table is exactly prod((N – n + 1):N) / N^n: for n = 5, (996:1000) are the five numerators and 1000^5 the five denominators together. The version that doesn’t overflow, prod((N – n + 1):N / N), does the same as the table: it divides each factor by 1000 before multiplying.
Check you’ve got it: why does it already go past 0.5 with only 38 emails, when there are 1000 codes?
Because what clashes isn’t single emails but pairs. With 38 emails there are pairs, and each one matches with probability 1/1000. That’s 703 chances of 1 in 1000: a well-known approximation gives , almost the exact 0.509. If you only think of your code against the others (37 chances), it seems almost impossible; the trick is that any pair counts.
The code
collision <- function(n, N = 1000) 1 - prod((N - n + 1):N) / N^n # P(some code repeated) among n emails p <- sapply(1:80, collision) # the probability for n = 1, 2, ..., 80 round(p[c(10, 20, 30, 37, 38, 40, 60, 80)], 3) # some values which(p > 0.5)[1] # first n with probability above 0.5 plot(1:80, p, type = "l", xlab = "n (emails)", ylab = "p") abline(h = 0.5, lty = 2, col = "red") # simulation: 10000 times, 38 random codes with replacement set.seed(2026) sim <- replicate(10000, any(duplicated(sample(1:1000, 38, replace = TRUE)))) mean(sim) # proportion of times with some repeated code
Output
[1] 0.044 0.174 0.356 0.490 0.509 0.546 0.836 0.961 [1] 38 [1] 0.513
How to read it
- The first line is the probabilities for 10, 20, 30, 37, 38, 40, 60 and 80 emails. With 10, 4.4 %; with 37, 49.0 %; with 38, 50.9 %; with 80, 96.1 %. Notice the jump between 37 and 38: that is where it crosses 50 %.
38: the smallest number of emails for which a repeated code is more likely than not. With only 3.8 % of the possible codes there is already more than an even chance of a clash.- The plot (redrawn in the site colours): the curve is S-shaped. It rises very slowly at first, shoots up between 20 and 60 emails and flattens near 1. The red dashed line is 0.5; it crosses it right at 38.
0.513: in 10,000 simulations with 38 emails, 51.3 % had some repeated code. The formula gave 0.509: the simulation confirms the calculation (the 0.004 difference is simulation error). In the drawing, both values sit one on top of the other.
In context: a 3-digit code is useless for identifying emails. With a few dozen emails, repeats are the norm. That is why real codes have 6 digits or more.
Questions you might ask
Why a function instead of writing the calculation for each ? Because the calculation is written once and sapply applies it to the 80 values. Also, the argument N = 1000 has a default value: collision(38) uses 1000 and collision(38, N = 365) solves the birthday problem.
What does any(duplicated(x)) do? duplicated marks with TRUE every value that had already appeared earlier in the vector; any says whether there is at least one TRUE. Together they answer “has anything repeated?”.
Why replicate(10000, …) and not a for loop? They do the same; replicate repeats an expression and collects the results in a vector, which is exactly what we need for the mean() afterwards. It is shorter and leaves less room for index mistakes.
Why doesn’t the simulation give exactly 0.509? Because it is a proportion over 10,000 repetitions. Its standard error is around , so a difference of 0.004 is to be expected.
What happens with 4-digit codes and many emails? N^n overflows. 10000^200 is , which R cannot store, so it gives Inf; the product on top does too, and Inf / Inf is NaN. The fix is to divide factor by factor: prod((N - n + 1):N / N), which multiplies numbers between 0 and 1 and never goes out of range. You will see it in the exercises, in “What’s wrong here?”.
Computing “at least two equal” by adding cases (two equal + three equal + …). It is long and something always gets left out. The complement, “all different”, is a single calculation.
Try it yourself
- Use
collision(n, N = 365)to solve the birthday problem: from how many people does it go above 0.5? (It should be 23.) - Rewrite the function with the factor-by-factor product and find the first above 0.5 with
N = 10000.
Program 3: Bayes in a table, with a function that works for everything
We want a function that, given the prior probabilities and the likelihoods, returns the full Bayes table (prior, likelihood, joint and posterior). We will use it three times: for the source of a spam, to see how the value of a “flagged” changes with the spam rate (with its plot), and to update twice when a second filter also flags the email. The catch: in the update, the posterior from the first step becomes the prior of the second, and the row names must be kept.
The idea
- The Bayes table is four columns that come from two:
joint = prior * likelihood(the tree branches) andposterior = joint / sum(joint)(Bayes). We put it in adata.frameso it reads well. - For the effect of the spam rate we use the two-branch formula with a vector of rates: R does the calculation for each at once. And
curve()draws the whole function between 0 and 1. - For the update: we apply the function with filter 1 and pass its
posteriorcolumn as thepriorof filter 2, usingsetNames()so the names are not lost.
Put into words, with whole numbers: imagine 10,000 emails. According to the prior, 5000 come from the campus, 3000 from lists and 2000 from outside. With their rates, 100 from the campus are spam (2 % of 5000), 300 from lists (10 % of 3000) and 1200 from outside (60 % of 2000): 1600 spam in total. If one of those 1600 reaches you, the probability that it comes from outside is . That’s all Bayes is: the joint is those 100, 300 and 1200 divided by 10,000, and the posterior is each one’s share of the total. The bayes() function just does these two calculations, for whatever vector you give it.
Before coding, think about what has to add up to 1 and what does not. The prior column adds up to 1, posterior adds up to 1, and joint adds up to the total probability, which is usually not 1.
The code
bayes <- function(prior, likelihood) {
joint <- prior * likelihood # each tree branch: P(cause and data)
data.frame(prior = prior, likelihood = likelihood,
joint = joint,
posterior = joint / sum(joint)) # Bayes: divide by the total probability
}
# 1) Where does a spam come from?
source_tab <- bayes(prior = c(campus = 0.50, lists = 0.30, external = 0.20),
likelihood = c(0.02, 0.10, 0.60))
round(source_tab, 4)
sum(source_tab$joint) # total probability of spam
# 2) The same filter (sensitivity 0.90, false alarm 0.02) with three spam rates
rates <- c(0.05, 0.25, 0.50)
round(0.90 * rates / (0.90 * rates + 0.02 * (1 - rates)), 4)
curve(0.90 * x / (0.90 * x + 0.02 * (1 - x)), from = 0, to = 1,
xlab = "proportion of spam (prior)", ylab = "P(spam | flagged)")
# 3) Two filters: the first flags it and then the second does too
step1 <- bayes(c(spam = 0.25, legitimate = 0.75), c(0.90, 0.02))
step2 <- bayes(setNames(step1$posterior, rownames(step1)), c(0.80, 0.05))
round(step1, 4)
round(step2, 4)
Output
prior likelihood joint posterior
campus 0.5 0.02 0.01 0.0625
lists 0.3 0.10 0.03 0.1875
external 0.2 0.60 0.12 0.7500
[1] 0.16
[1] 0.7031 0.9375 0.9783
prior likelihood joint posterior
spam 0.25 0.90 0.225 0.9375
legitimate 0.75 0.02 0.015 0.0625
prior likelihood joint posterior
spam 0.9375 0.80 0.7500 0.9959
legitimate 0.0625 0.05 0.0031 0.0041
How to read it
This is the output that looks most like what the exam asks for, so let us go slowly:
- First table (
source_tab). Each row is a source.jointholds the tree branches: 0.01, 0.03 and 0.12.posterioris the joint over its sum: if an email is spam, it comes from outside with probability 0.75. Compared with the prior (0.20), the data “is spam” multiplies the probability that it is external by 3.75. 0.16: the sum of thejointcolumn, the total probability of spam. It is Bayes’ denominator.0.7031 0.9375 0.9783: with 5 %, 25 % and 50 % spam. Same filter, three different answers.- The plot from
curve()(redrawn in the site colours) draws that function for every rate from 0 to 1. The curve rises very fast at first and then flattens: with little spam, each point of rate changes the answer a lot; with lots of spam, hardly at all. The dotted diagonal (not drawn by RStudio; I added it for comparison) would be “no filter”: the posterior equal to the prior. Everything the curve sits above the diagonal is what the filter contributes. step1: the table for one filter with 25 % spam. Thespamrow gives 0.9375 andlegitimate0.0625; they add up to 1.step2: thepriorcolumn is no longer 0.25/0.75: it is theposteriorfrom step 1 (0.9375/0.0625). With the second filter (sensitivity 0.80, false alarm 0.05) also flagging, the probability of spam rises to 0.9959. Look at the legitimate joint: 0.0031 ().
In context: a single “flagged” leaves 6.25 % doubt; two “flagged” from independent filters, less than 0.5 %. That is how real filters work: they pile up clues and update with Bayes. And the plot explains why the same filter seems worse in an inbox with little spam.
The Bayes table, row by row
The first table in the output, with the calculation for each cell:
| Source | prior | likelihood | joint | posterior | Why |
|---|---|---|---|---|---|
| campus | 0.50 | 0.02 | lots of email, hardly any spam | ||
| lists | 0.30 | 0.10 | middle ground on both | ||
| external | 0.20 | 0.60 | little email, but nearly all spam | ||
| Sum | 1 | 0.72 | 0.16 | 1 | the sum of joint is the denominator |
The likelihood column adds up to 0.72 and has no reason to add up to 1: each number is the spam rate of a different source. The campus has the biggest prior and ends up with the smallest posterior: what decides it isn’t where most email comes from, but where most spam comes from.
Check you’ve got it: if external email dropped to 10 % and campus email rose to 60 %, would “external” still be the most likely source of a spam?
The joints would be , and , which add up to 0.102. The posteriors, dividing by 0.102: campus 0.1176, lists 0.2941 and external 0.5882. Yes, it is still the most likely, although now with just over half. You can check it with bayes(c(campus = 0.60, lists = 0.30, external = 0.10), c(0.02, 0.10, 0.60)).
Questions you might ask
Why return a data.frame and not just the posterior? Because in the exam you have to justify the result, and the table shows the steps: the joint is the numerator and its sum the denominator. Also, round(source_tab, 4) rounds the four columns at once.
Why setNames(step1$posterior, rownames(step1))? step1$posterior is a vector without names; passed as it is, the step 2 table would have rows 1 and 2 and you would not know which is which. setNames gives it the row names from step 1 (spam, legitimate).
What is the x inside curve()? It is the name curve gives to the variable: it draws the expression for many values of x between from and to. It must be called x; if you write rate, you get an error.
Why does updating in two steps give the same as doing it at once? If the filters are independent given the type of email, multiplying by both likelihoods at once ( and ) gives the same posterior as doing it in two steps. Try it: bayes(c(0.25, 0.75), c(0.90 * 0.80, 0.02 * 0.05)).
What is the function good for outside this example? For any Bayes problem with a partition: medical tests, machines that make faulty parts, systems that detect something. It goes straight into your exam script.
Passing the joint column to the second step instead of the posterior. The joint does not add up to 1, and the prior of the second step has to. If the prior column in step 2 does not add up to 1, something is wrong.
Try it yourself
- Repeat the two-step update, but with an inbox where only 5 % is spam. What is the posterior after the first “flagged” and after the second?
- Use
bayes()with the data from the servers example in the exercises (ULPGC 0.60, Gmail 0.25, others 0.15; rates 0.01, 0.08, 0.40) and check that the total probability is 0.086.
Common mistakes in this practice
probin the wrong order.samplegives each probability to the element in the same position. Check the proportion after simulating.- Forgetting
set.seed()when comparing. Without a seed, each run gives different numbers and you cannot compare with what you have written down. - Mistaking the estimate for the probability. 0.9283 is not “the probability”: it is an estimate of 0.9375 from 1200 flagged emails.
- Overflowing with big powers.
N^nandprod()of many big numbers giveInf. Divide factor by factor. - Losing the names in the update. Use
setNames()or pass a named vector. - Misreading the joint. The
jointcolumn is not a conditional probability and does not add up to 1: its sum is the total probability.
Try it in the R playground
Open the site’s R playground and paste this short script. It puts the three programs together in a minimal version so you can see the outputs and plots at once.
set.seed(2026)
is_spam <- runif(2000) < 0.25
plot(cumsum(is_spam) / seq_len(2000), type = "l", ylim = c(0, 0.5))
abline(h = 0.25, lty = 2)
collision <- function(n, N = 1000) 1 - prod((N - n + 1):N / N) # version that does not overflow
which(sapply(1:100, collision) > 0.5)[1]
bayes <- function(prior, likelihood) {
joint <- prior * likelihood
data.frame(prior, likelihood, joint, posterior = joint / sum(joint))
}
bayes(c(spam = 0.25, legitimate = 0.75), c(0.90, 0.02))
What to look at:
- In Plots, the line that sticks to 0.25. Remove the
set.seedand run it several times: the start changes, the end does not. - The second output must be 38, with the version of the function that divides factor by factor.
- In Environment you will see
bayesas a function: typebayeswithout brackets in the console to see its code. - Type
?replicatein the console: the help opens in the Help panel.
Summary
- A simulation follows the same order as the tree: first the cause (
runif() < rate), then what depends on it (ifelse()with each branch’s probability). - The cumulative proportion (
cumsum(x) / seq_len(n)) approaches the probability, andmean(x[condition])estimates a conditional probability. - For “at least one”, the complement; for probabilities with big powers, multiply factor by factor so as not to overflow.
replicate()+mean()estimates any probability you know how to simulate, and is a way to check a formula.- A
bayes(prior, likelihood)function that returns the full table solves any Bayes problem with a partition and works for updating in several steps. - The value of a “positive” depends on the base rate: the same filter gives 0.70 or 0.98 depending on how much spam there is.
Checklist: have you practised it?
- Have you run the three programs and checked the outputs?
- Can you explain why
is_spam[flagged]gives a conditional probability? - Could you find the first above 0.5 for another number of codes?
- Do you understand why
N^noverflows and how to avoid it? - Can you read a Bayes table and say which column is the numerator and which sum gives the denominator?
- Have you tried the “Try it yourself” tasks without looking at the theory?
If you said yes to almost everything, you are ready for the probability exercises, where I no longer give you the code. See you there!
Next step: exercisesProbability — exam-style ME1 exercises with the spam filter: counting, tables, total probability and Bayes (and the row that should have been a column)Did this article help you? Here is how you can support SergioLearns →



