R intensive 4: limit theorems and sampling — exercises with the Spanish Christmas lottery, functions that return lists and the bell curve over the histogram (and the curve that would not show)
For the faculty’s lottery syndicate I simulated five thousand Christmas draws in R, drew the histogram and put the normal curve from the central limit theorem on top: the curve was nowhere to be seen. It was there, flat against the axis, because the histogram counted syndicates (hundreds) and the curve measured density (thousandths); a freq = FALSE was missing.
This article is the hands-on part of block 4 of the R intensive. The theory (Monte Carlo, cumsum, functions that return lists, overlaid plots with curve(…, add = TRUE) and Chebyshev checked by simulation) is in R intensive 4: limit theorems and sampling. The statistics (law of large numbers, central limit theorem, Chebyshev’s inequality) are taken as known: if you need them, review the ME1 inequalities and limit theorems exercises and the sampling distributions exercises. Here the point is to see the theorems with your own eyes: simulate, measure and draw.
Table of Contents
How to use this article
- Open the R playground (or RStudio). With the same seed and the same order, you will get the same numbers.
- Level 1, reproduce and read; level 2, write a Monte Carlo function that returns a list; level 3, a full problem in the format of the ME1 exam script.
- The solutions are folded, with the reason for every decision.
- Finish with the test and copy “For your script” into your
.R.
The draw in the exercise. A tenth-share ticket (décimo) costs 20 € and the prizes we use are a simplified version of the Spanish Christmas lottery (no “approximations”, hundreds or endings), with these probabilities per ticket: 400,000 € (1 in 100,000), 125,000 € (1), 50,000 € (1), 20,000 € (2), 6,000 € (8), the small prize or pedrea of 100 € (1794) and the refund of 20 € (9986). They are not the official figures for any year: they are for programming, not for deciding whether to play.
Level 1: reproduce and read the law of large numbers
prizes <- c(400000, 125000, 50000, 20000, 6000, 100, 20, 0)
prob <- c(1, 1, 1, 2, 8, 1794, 9986, 0) / 1e5
prob[8] <- 1 - sum(prob) # the rest: win nothing
mu <- sum(prizes * prob) # what a ticket wins on average
sigma <- sqrt(sum((prizes - mu)^2 * prob))
round(c(mu = mu, sigma = sigma), 2)
set.seed(22)
x <- sample(prizes, 1e5, replace = TRUE, prob = prob) # 100,000 simulated tickets
table(x)
run_mean <- cumsum(x) / seq_along(x)
round(run_mean[c(10, 100, 1000, 10000, 1e5)], 2)
plot(run_mean, type = "l", log = "x", main = "What a ticket wins on average",
xlab = "Tickets played (log scale)", ylab = "Running mean (euros)")
abline(h = mu, lty = 2, col = "red")
- Each 20 € ticket wins 10.42 € on average. What does the standard deviation, 1338.75 €, tell you compared with that mean?
- In 100,000 tickets, did the jackpot (el Gordo) come up? How many prizes of 6000 € or more are there?
- What does
cumsum(x) / seq_along(x)do? - After 100,000 tickets, the running mean is 7.16 €, far from 10.42. Is the law of large numbers failing?
cumsum(x) is the vector of running totals (what has been won up to ticket 1, 2, 3…) and seq_along(x) is 1, 2, 3… up to the length of x. Dividing one by the other, element by element, gives the mean after each ticket.
Level 2: a Monte Carlo function that returns a list
Look only at the small prizes: = what a ticket wins in pedrea or refund (100 €, 20 € or 0 €, with the probabilities above). Write sim_mean(n, B, values, prob) that simulates the mean of tickets times and returns a list with four elements: means (the means), mean (their mean), sd (their standard deviation) and sd_theory ().
Then, with set.seed(5) and , call the function with = 1, 10, 50 and 200 and present a table with n, mean, sd and sd_theory (3 decimal places).
A list is created with list(name = value, …) and read with r$mean or r[["mean"]]. For the table, an anonymous function inside sapply: sapply(c(1, 10, 50, 200), function(n) { r <- sim_mean(…); c(n = n, mean = r$mean, …) }).
Level 3 (challenge): the syndicate’s 200 tickets, in the exam format
Exercise (15 points). The faculty syndicate plays 200 tickets with different numbers. We are interested in , the total it wins in small prizes (pedrea and refund), and the mean per ticket .
- a) (3 points) Work out in R the mean and standard deviation of for one ticket, and the theoretical mean and standard deviation of (2 decimal places).
- b) (4 points) With
set.seed(2412)and yoursim_meanfunction, simulate 5000 syndicates. Give the mean and standard deviation of the 5000 totals and compare them with the theoretical ones. - c) (4 points) Draw the histogram of the totals on the density scale and overlay the normal curve given by the central limit theorem. Estimate by simulation and with the normal.
- d) (4 points) Chebyshev’s inequality says that . Compute that probability from the simulation and say how far below the bound it is.
To overlay, first hist(…, freq = FALSE) and then curve(dnorm(x, mean, sd), add = TRUE). The add = TRUE is what draws the curve on top instead of in a new plot.
Solutions
Level 1
Before you open the solution, the plan. This level mixes two things worth keeping apart: what the model says (the probabilities of the draw) and what came out in your 100,000 tickets. and come from the model, with sum(prizes * prob), without simulating anything; table(x) and the running mean come from the simulation. The 7.16 is what came out; the 10.42 is what the model says; and the law of large numbers is about how the first gets closer to the second.
And why cumsum(x) / seq_along(x) instead of a plain mean(x)? Because mean(x) gives a single number, the final one, and the question is about the path: how the mean moves ticket by ticket. That path is exactly what gets plotted.
See the level 1 solution
prizes <- c(400000, 125000, 50000, 20000, 6000, 100, 20, 0) prob <- c(1, 1, 1, 2, 8, 1794, 9986, 0) / 1e5 prob[8] <- 1 - sum(prob) mu <- sum(prizes * prob) sigma <- sqrt(sum((prizes - mu)^2 * prob)) round(c(mu = mu, sigma = sigma), 2) set.seed(22) x <- sample(prizes, 1e5, replace = TRUE, prob = prob) table(x) run_mean <- cumsum(x) / seq_along(x) round(run_mean[c(10, 100, 1000, 10000, 1e5)], 2)
Output:
mu sigma
10.42 1338.75
x
0 20 100 6000 20000 125000
88170 10001 1820 4 3 2
[1] 10.00 4.00 3.86 3.69 7.16
- That the mean represents almost nobody. A ticket wins 10.42 € on average (you lose 9.58 € of every 20), but the standard deviation is more than a hundred times the mean: almost every ticket wins 0 or 20 €, and a tiny few win hundreds of thousands. Those tiny few hold the mean up.
- The jackpot did not come up in 100,000 tickets (neither 400000 nor 50000 appear). There are 2 second prizes, 3 of 20,000 € and 4 of 6,000 €: nine big prizes in all.
- The mean after each ticket: element 10 is the mean of the first 10, element 1000 the mean of the first 1000, and so on.
- It is not failing: it is slow. The law of large numbers says the mean approaches as grows, not that with 100,000 it is already close. With such a heavy tail, the mean depends on whether a big prize falls or not: here the jackpot and the third prize are missing, and they are 4.50 € of the 10.42 mean.
plot(run_mean, type = "l", log = "x", main = "What a ticket wins on average",
xlab = "Tickets played (log scale)", ylab = "Running mean (euros)")
abline(h = mu, lty = 2, col = "red")
In the plot, the running mean jumps every time a big prize falls (the first second prize, at ticket 18,088, lifts it above 10 in one go) and in between it drifts down slowly, because almost every ticket wins 0 or 20. The logarithmic horizontal axis lets you see the first ten tickets and the last hundred thousand at the same time.
Why the mean stops at 7.16. The solution says the jackpot and the third prize are missing. You can see where each euro of the 10.42 comes from by multiplying each prize by its probability:
share <- prizes * prob # what each prize puts into the mean names(share) <- format(prizes, scientific = FALSE, trim = TRUE) round(share, 2) round(sum(share[prizes >= 6000]), 2) # the part of the mean the big prizes put in round(c(sigma = sigma, simulated_sd = sd(x)), 2)
Output:
400000 125000 50000 20000 6000 100 20 0
4.00 1.25 0.50 0.40 0.48 1.79 2.00 0.00
[1] 6.63
sigma simulated_sd
1338.75 571.06
Prizes of 6000 € or more put in 6.63 € of the 10.42, almost two thirds, and they come up 13 times in every 100,000 tickets. The jackpot alone puts in 4.00 €. That is why a 100,000-ticket simulation without a jackpot falls short: it is missing exactly those 4.00 € and the 0.50 of the third prize. And the standard deviation of the simulated tickets, 571.06 €, is less than half the model’s: what stretches it most is the prize that did not fall.
Answering with sd(x). That is the standard deviation of what came out in your simulation, not of the draw, and here it is less than half. When the problem gives the probabilities, and are computed from them.
Check you’ve got it: if one more jackpot had fallen in the 100,000 tickets, what would the final running mean be?
400,000 € spread over 100,000 tickets is 4 € more per ticket: from 7.16 to 11.16, now above 10.42. A single ticket moves the final mean by 4 €: with such a heavy tail, 100,000 tickets are still few.
Level 2
The plan, before the code. The function has two layers: one simulation is the mean of tickets (mean(sample(…))), and the Monte Carlo is repeating that simulation times (replicate). Thought of like that, it almost writes itself.
First, pin down . Only small prizes and refunds count, so a ticket with a big prize is worth 0 for : that is why the probability of 0 is and the level 1 prob vector is not reused. With these three figures, €: the mean you will see repeated in the mean column.
The obvious route would be a for loop filling a vector of means. It works, but you have to create the vector first and keep track of the index by hand; replicate(B, …) does the same in one line and cannot get a position wrong.
See the level 2 solution
# sim_mean(): Monte Carlo of the mean of n values of a discrete variable, repeated B times
sim_mean <- function(n, B, values, prob) {
stopifnot(n >= 1, B >= 2, length(values) == length(prob), abs(sum(prob) - 1) < 1e-8)
means <- replicate(B, mean(sample(values, n, replace = TRUE, prob = prob)))
mu <- sum(values * prob)
sigma <- sqrt(sum((values - mu)^2 * prob))
list(means = means, # the B means, in case you want to plot them
mean = mean(means),
sd = sd(means),
sd_theory = sigma / sqrt(n))
}
small <- c(0, 20, 100)
ps <- c(1 - 0.09986 - 0.01794, 0.09986, 0.01794)
set.seed(5)
tab <- t(sapply(c(1, 10, 50, 200), function(n) {
r <- sim_mean(n, 2000, small, ps)
c(n = n, mean = r$mean, sd = r$sd, sd_theory = r$sd_theory)
}))
round(tab, 3)
Output:
n mean sd sd_theory [1,] 1 3.990 14.422 14.317 [2,] 10 3.866 4.597 4.527 [3,] 50 3.836 2.045 2.025 [4,] 200 3.799 1.001 1.012
How to read it: the mean column always stays near € (the mean of a mean is the variable’s mean), and the sd column falls with just like sd_theory: 14.4 with one ticket, 4.6 with ten, 1.0 with two hundred. Multiplying by 100 divides the standard deviation by , and the simulation confirms it column by column.
Why it is written this way:
- A list, not a vector. The result has pieces of different shapes: a vector of 2000 means and three loose numbers. A vector would mix them (the 2000 means and the three summaries, all together); a list keeps each piece with its name and its shape.
- Also returning
means. The summaries are enough for the table, but level 3 needs the histogram: if the function only returned the mean and the standard deviation, you would have to simulate again. - The check
abs(sum(prob) - 1) < 1e-8. Probabilities are computed with decimals and do not add up to exactly 1 (they can give 0.9999999999); comparing with== 1would fail for no reason. - The anonymous function in
sapply.sim_meanreturns a list, andsapplyneeds every call to give a vector of the same length to build the matrix: the anonymous function pulls the four numbers out of the list.
Level 3
Before you open the solution, the map. Each part builds on the one before, and in each one there is an obvious route that is not the right one:
| Part | Route | Why not the obvious one |
|---|---|---|
| a) | and | What adds up are the variances of the 200 independent tickets, not the standard deviations: would give 2863.36 € |
| b) | sim_mean(200, 5000, …) and multiply the means by 200 | No need for another simulation: , and the function is already written and tested |
| c) | hist(…, freq = FALSE), curve(dnorm(…), add = TRUE) and mean(tot >= 1000) | The mean of a vector of TRUE and FALSE is the proportion of TRUE: the relative frequency, without counting by hand |
| d) | r$means against | The inequality is written with ; with tot it also works, but then the distance is |
In c) and d) two figures from different places are compared, the simulation and the model: the comparison is the answer.
See the level 3 solution
a) The theoretical values (3 points).
# ==== Exercise 3a: mean and standard deviation of Y and S ==== mu_y <- sum(small * ps) sg_y <- sqrt(sum((small - mu_y)^2 * ps)) round(c(mu_y = mu_y, sg_y = sg_y, mu_S = 200 * mu_y, sg_S = sg_y * sqrt(200)), 2)
Output:
mu_y sg_y mu_S sg_S 3.79 14.32 758.24 202.47
In small prizes a ticket wins 3.79 € on average with a standard deviation of 14.32 €. For 200 independent tickets, € and €: the mean is multiplied by 200, but the standard deviation only by .
b) 5000 syndicates (4 points).
# ==== Exercise 3b: simulate 5000 syndicates ==== set.seed(2412) r <- sim_mean(200, 5000, small, ps) tot <- 200 * r$means # from the mean per ticket to the syndicate's total round(c(mean = mean(tot), sd = sd(tot)), 2)
Output:
mean sd 756.46 205.17
Mean of the totals 756.46 € (theoretical 758.24) and standard deviation 205.17 € (theoretical 202.47): within 1.5 % in both cases.
c) Histogram with its normal (4 points).
# ==== Exercise 3c: density histogram + CLT normal ====
hist(tot, breaks = seq(0, 1800, by = 100), freq = FALSE,
main = "What the syndicate wins in small prizes", xlab = "Total (euros)", ylab = "Density")
curve(dnorm(x, 200 * mu_y, sg_y * sqrt(200)), add = TRUE, lwd = 2, col = "red")
round(mean(tot >= 1000), 4) # simulated
round(1 - pnorm(1000, 200 * mu_y, sg_y * sqrt(200)), 4) # CLT normal
Output:
[1] 0.134 [1] 0.1162
In the plot, the red curve follows the bars well: with 200 tickets the total is already bell-shaped, even though a single ticket is very skewed (almost all zeros). There is a little right skew: the bars from 1100 to 1600 sit slightly above the curve. That is why the normal falls short in the tail: is 0.1340 in the simulation and 0.1162 with the normal. One syndicate in seven or eight wins at least 1000 € in small prizes (out of 4000 € played).
Writing curve(dnorm(x, 758.24, 202.47), add = TRUE) without freq = FALSE in the histogram: the bars measure how many syndicates fall in each band (hundreds) and the curve measures density (thousandths), so the curve comes out squashed against the axis. It is the story from the start, and you will see it drawn in “What’s wrong here?”.
d) Chebyshev against the simulation (4 points).
# ==== Exercise 3d: Chebyshev's bound with k = 2 ==== k <- 2 round(mean(abs(r$means - mu_y) >= k * sg_y / sqrt(200)), 4) # simulated 1 / k^2 # bound
Output:
[1] 0.0442 [1] 0.25
The simulation gives 0.0442 and the bound is 0.25: Chebyshev is right (the probability is below it), but it is five or six times higher than the real value. That is to be expected: Chebyshev holds for any variable with a finite variance, so it cannot take advantage of this one being bell-shaped. With the normal, the probability would be about 0.05.
How it is marked (indicative, my own, not official). a: 2 points for and of and 1 for moving to with . b: 2 for using the function with a seed and 2 for comparing. c: 2 for the density plot with the curve on top and 2 for the two probabilities. d: 2 for the simulated frequency and 2 for comparing it with the bound.
Two checks that are not in the solution. The first, why and not ; the second, that Chebyshev gives the same with the total as with the mean per ticket:
round(c(right = sg_y * sqrt(200), wrong = 200 * sg_y), 2) # sd of S: root of n, not n round(mean(abs(tot - 200 * mu_y) >= 2 * sg_y * sqrt(200)), 4) # Chebyshev with the total, not the mean round(2 * (1 - pnorm(2)), 4) # what the normal would say
Output:
right wrong 202.47 2863.36 [1] 0.0442 [1] 0.0455
The «wrong» standard deviation, 2863.36 €, is about fourteen times the one the simulation measures (205.17 €): with it, the curve in part c) would look nothing like the bars. The frequency with the total is the same, 0.0442, because multiplying both sides of by 200 gives : it is the same event, written in the syndicate’s euros. And the 0.0455 is the solution’s «about 0.05»: the probability that a normal lands more than two standard deviations from its mean.
Check you’ve got it: with k = 3, what bound does Chebyshev give and what would the normal give?
The bound is . The normal gives 2 * (1 - pnorm(3)), which is 0.0027. With k = 3 the bound is about forty times the normal’s probability: the further out you look, the worse Chebyshev does, because it only uses the variance and does not know the sum is bell-shaped.
What’s wrong here?
Snippet 1. The story: the histogram of the totals and its curve.
hist(tot, breaks = seq(0, 1800, by = 100), main = "Totals", xlab = "Euros") curve(dnorm(x, 758.24, 202.47), add = TRUE, lwd = 2, col = "red")
There is no error message: the bug only shows in the plot. On the left, the histogram in frequencies (the tallest bar, 986 syndicates) and the curve, whose maximum height is 0.002, flat against the axis. On the right, the same with freq = FALSE: the bars become density (frequency / (5000 · 100)) and the curve fits.
Overlaying a density on a frequency histogram. Fix: freq = FALSE in hist whenever a curve is going on top.
Snippet 2. Using the function’s result.
r["mean"] * 200
Output:
Error in r["mean"] * 200 : non-numeric argument to binary operator
With a list, the single bracket [ ] returns another list (a sublist with the element mean), and a list cannot be multiplied. To get the value out you need double brackets or the dollar sign.
Think of the list as a train: r["mean"] gives you the carriage (with its label) and r[["mean"]] or r$mean, what is inside the carriage.
r[["mean"]] * 200 r$mean * 200
Output:
[1] 756.456 [1] 756.456
Snippet 3. The running mean of the first ten tickets from level 1.
y <- x[1:10] wrong <- cumsum(y) / length(y) round(wrong, 2)
Output:
[1] 0 0 10 10 10 10 10 10 10 10
length(y) is a single number, 10: every running total is divided by 10. The last value is right (the mean of the ten), but the first is what ticket 1 won divided by 10, which is the mean of nothing. Notice that the result never goes down (a running total of prizes cannot go down), when the real mean goes down from 33.33 to 10 as tickets without a prize pile up: the only prize, the pedrea on the third ticket, is shared among more and more tickets.
Dividing the running total by the overall count. Fix: by the number of tickets each total covers, seq_along(y).
round(cumsum(y) / seq_along(y), 2)
Output:
[1] 0.00 0.00 33.33 25.00 20.00 16.67 14.29 12.50 11.11 10.00
Test: read the code
Ten questions on reading code. They do not count and you can repeat them.
What does this code print?
x <- c(4, 0, 2, 6) cumsum(x) / seq_along(x)
[1] 4 2 2 3[1] 1 1 1.5 3[1] 4 4 6 12[1] 3
Solution
Answer: [1] 4 2 2 3
cumsum(x) = 4, 4, 6, 12 and seq_along(x) = 1, 2, 3, 4. Dividing element by element: 4, 2, 2, 3, the mean after each value.
What does the last line print?
r <- list(mean = 3.8, sd = 1.2) class(r["mean"])
[1] "list"[1] "numeric"[1] "character"- An error
Solution
Answer: [1] "list"
r["mean"] is a one-element list (the carriage with its label). For the number inside: r[["mean"]] or r$mean.
What number does it print? Write just the number.
v <- c(0, 10) p <- c(0.8, 0.2) sum(v * p)
Solution
Answer: 2
0 · 0.8 + 10 · 0.2 = 2: the variable’s mean.
What does the second line do?
hist(rnorm(500), freq = FALSE) curve(dnorm(x), add = TRUE)
- It draws the standard normal density on top of the histogram
- It opens a new plot with the curve alone
- It gives an error because
xis not defined - It draws the curve squashed against the axis
Solution
Answer: It draws the standard normal density on top of the histogram
curve evaluates the expression over a grid of x values and, with add = TRUE, paints it on the open plot. With the histogram in density, both are on the same scale.
How many elements does m have?
m <- replicate(300, mean(sample(1:6, 10, replace = TRUE))) length(m)
[1] 300[1] 10[1] 3000[1] 1
Solution
Answer: [1] 300
replicate(300, …) evaluates the mean of 10 rolls 300 times and returns the 300 means.
If sd(x) is 12 for a single observation, roughly what do you expect sd(m) to give?
m <- replicate(5000, mean(sample(x, 36, replace = TRUE))) sd(m)
- About 2
- About 12
- About 0.33
- About 432
Solution
Answer: About 2
The standard deviation of the mean of independent observations is : 12 / 6 = 2.
What is wrong with this code?
f <- function(n) {
m <- replicate(1000, mean(rexp(n)))
list(means = m, sd = sd(m))
}
r <- f(20)
r["sd"] * sqrt(20)- Error: a list cannot be multiplied
- Nothing: it prints a number close to 1
- Error because
listdoes not accept vectors return()is missing beforelist
Solution
Answer: Error: a list cannot be multiplied
The function is fine; the bug is in reading the result. r["sd"] * sqrt(20) gives “non-numeric argument to binary operator”.
About Chebyshev’s inequality checked by simulation, mark true or false.
k <- 2 c(simulated = mean(abs(m - mu) >= k * s), bound = 1 / k^2)
- With k = 2, the bound is 0.25.
- If the simulation gives 0.05, Chebyshev holds.
- If the simulation gives 0.05, Chebyshev fails because it does not match 0.25.
- With k = 3, the bound is 1/3.
Solution
- T — With k = 2, the bound is 0.25.
- T — If the simulation gives 0.05, Chebyshev holds.
- F — If the simulation gives 0.05, Chebyshev fails because it does not match 0.25.
- F — With k = 3, the bound is 1/3.
Chebyshev is an upper bound: it says the probability is no more than , not that it equals it. With k = 3, the bound is 1/9.
What does this code print?
tot <- c(800, 1200, 950, 1000, 600) mean(tot >= 1000)
[1] 0.4[1] 0.2[1] 2[1] 910
Solution
Answer: [1] 0.4
tot >= 1000 gives FALSE TRUE FALSE TRUE FALSE; the mean of a logical vector is the proportion of TRUEs: 2/5 = 0.4.
What does this code print?
m <- function(n) sqrt(n) sapply(c(1, 4, 100), m)
[1] 1 2 10[1] 1 4 100- A list with three elements
[1] 13
Solution
Answer: [1] 1 2 10
sapply(v, f) applies f to each element: , , . It is the factor is divided by in the mean of data.
Try it in the R playground
Paste this script into the R playground. It is the central limit theorem with a die, in ten lines.
set.seed(3)
means <- function(n, B = 3000) replicate(B, mean(sample(1:6, n, replace = TRUE)))
par(mfrow = c(1, 3))
for (n in c(1, 5, 30)) {
m <- means(n)
hist(m, freq = FALSE, breaks = 20, main = paste("n =", n), xlab = "Mean of n rolls")
curve(dnorm(x, 3.5, sqrt(35/12) / sqrt(n)), add = TRUE, col = "red", lwd = 2)
}
par(mfrow = c(1, 1))
What to look at:
- With , the histogram is flat (a fair die) and the curve looks nothing like it.
- With the bell shape already appears; with , the curve fits.
- Look at the horizontal axis: narrower each time. The standard deviation of the mean is .
- Remove
freq = FALSEand run again: the curves vanish against the axis, as in the story.
Cheat sheet: Monte Carlo in R
The essentials in 30 seconds: simulate one experiment with a function, repeat it with replicate, summarise with mean, sd and proportions, and compare with the theory (, , the normal). If you return several things, a list. To overlay a curve, a density histogram and curve(…, add = TRUE).
| I want to… | Code | Result |
|---|---|---|
| Simulate a discrete variable | sample(v, n, replace = TRUE, prob = p) | vector |
| and of a discrete variable | sum(v * p), sqrt(sum((v - mu)^2 * p)) | numbers |
| Running mean | cumsum(x) / seq_along(x) | vector |
| See it converge | plot(m, type = "l", log = "x") + abline(h = mu) | plot |
| Means of samples | replicate(B, mean(sample(…))) | B means |
| Return several things | list(means = m, mean = mean(m)) | list |
| Read an element | r$mean or r[["mean"]] | the value |
| Histogram with a curve | hist(x, freq = FALSE) + curve(dnorm(x, mu, s), add = TRUE) | bell on top |
| Simulated proportion | mean(tot >= 1000) | probability |
| Chebyshev | mean(abs(m - mu) >= k * s) against 1 / k^2 | frequency ≤ bound |
Templates from the exercises: full ticket, €, €; small prizes, €, €; syndicate of 200, €, €.
| Symptom | Likely cause |
|---|---|
| The curve does not show over the histogram | Frequency histogram: freq = FALSE is missing |
| The curve appears in a new plot | add = TRUE is missing in curve |
| “non-numeric argument to binary operator” with a list | r["x"] instead of r[["x"]] or r$x |
| The running mean never goes down | Dividing by length(x) instead of seq_along(x) |
| The simulated mean does not approach | Heavy tail (rare prizes): it needs an enormous |
Before you hand it in, ask yourself:
- Have I compared the simulated values with the theoretical ones (mean, standard deviation, probability)?
- Are my histograms with a curve on the density scale?
- Do I read list elements with
$or[[ ]]? - Have I said how many repetitions I did and with which seed?
For your script
The block’s code, commented and without problem statements, for your .R.
# ===================== Block R4: Monte Carlo, LLN, CLT and Chebyshev =====================
# moments(values, prob): mean and standard deviation of a discrete variable
moments <- function(values, prob) {
stopifnot(length(values) == length(prob), abs(sum(prob) - 1) < 1e-8)
mu <- sum(values * prob)
c(mu = mu, sigma = sqrt(sum((values - mu)^2 * prob)))
}
# running_mean(x): mean after each observation (to see the LLN)
running_mean <- function(x) cumsum(x) / seq_along(x)
# sim_mean(n, B, values, prob): B means of n values, with their simulated and theoretical sd
sim_mean <- function(n, B, values, prob) {
stopifnot(n >= 1, B >= 2, length(values) == length(prob), abs(sum(prob) - 1) < 1e-8)
means <- replicate(B, mean(sample(values, n, replace = TRUE, prob = prob)))
m <- moments(values, prob)
list(means = means, mean = mean(means), sd = sd(means), sd_theory = m[["sigma"]] / sqrt(n))
}
# hist_normal(x, mu, s, ...): density histogram with N(mu, s) on top
hist_normal <- function(x, mu = mean(x), s = sd(x), ...) {
hist(x, freq = FALSE, ...)
curve(dnorm(x, mu, s), add = TRUE, lwd = 2, col = "red")
}
# chebyshev(m, mu, s, k): simulated frequency of |m - mu| >= k s against the bound 1/k^2
chebyshev <- function(m, mu, s, k = 2) c(simulated = mean(abs(m - mu) >= k * s), bound = 1 / k^2)
# Quick check with the syndicate round(moments(small, ps), 2) chebyshev(r$means, mu_y, sg_y / sqrt(200), k = 2)
Output:
mu sigma 3.79 14.32 simulated bound 0.0442 0.2500
In hist_normal, the ... pass to hist everything that is not mu or s: you can call it with breaks = 20, main = "…", xlab = "…" without declaring those arguments one by one.
What next?
If cumsum, lists or curve(…, add = TRUE) still wobble, go back to the block’s theory, R intensive 4: limit theorems and sampling. And for the proofs and the pen-and-paper calculations, the ME1 inequalities and limit theorems exercises.
The next block, the last one, is R intensive 5: estimation and intervals: optimize and optim for maximum likelihood, functions that return intervals with their checks and how to organise the exam script.
Did this article help you? Here is how you can support SergioLearns →
Next blockR intensive 5: estimation and intervals — optimize and optim for maximum likelihood, your own interval functions and the exam scriptBlock theory: Monte Carlo, lists and curves over histogramsR intensive 4: limit theorems and samplingCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script


