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.

How to use this article

  1. Open the R playground (or RStudio). With the same seed and the same order, you will get the same numbers.
  2. 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.
  3. The solutions are folded, with the reason for every decision.
  4. 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")
  1. Each 20 € ticket wins 10.42 € on average. What does the standard deviation, 1338.75 €, tell you compared with that mean?
  2. In 100,000 tickets, did the jackpot (el Gordo) come up? How many prizes of 6000 € or more are there?
  3. What does cumsum(x) / seq_along(x) do?
  4. 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: Y Y = 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 n n tickets B B times and returns a list with four elements: means (the B B means), mean (their mean), sd (their standard deviation) and sd_theory (σ/n \sigma/\sqrt{n} ).

Then, with set.seed(5) and B=2000 B = 2000 , call the function with n n = 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 S S , the total it wins in small prizes (pedrea and refund), and the mean per ticket Yˉ=S/200 \bar{Y} = S/200 .

  • a) (3 points) Work out in R the mean μ \mu and standard deviation σ \sigma of Y Y for one ticket, and the theoretical mean and standard deviation of S S (2 decimal places).
  • b) (4 points) With set.seed(2412) and your sim_mean function, 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 P(S≥1000) P(S \ge 1000) by simulation and with the normal.
  • d) (4 points) Chebyshev’s inequality says that P(∣Yˉ−μ∣≥2σ/200)≤1/4 P\big(|\bar{Y} – \mu| \ge 2\sigma/\sqrt{200}\big) \le 1/4 . 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. μ \mu and σ \sigma 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
  1. 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.
  2. 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.
  3. 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.
  4. It is not failing: it is slow. The law of large numbers says the mean approaches μ \mu as n n 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")
Running mean of 100,000 ticketsOutput of plot with type equal to l and a logarithmic horizontal axis: the running mean starts between 0 and 20, falls towards 4, jumps above 10 at ticket 18,088 with a second prize, falls again and jumps again near 89,406; it ends at 7.16, below the 10.42 line.051015202530Running mean (euros)1101001,00010,000100,000μ = 10.422nd prize (receipt 18,088)7.16Tickets played (log scale)
Redrawn in the site colours: each jump is a big prize; between jumps, the mean drifts down slowly.

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 σ \sigma 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, μ \mu and σ \sigma 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 n n tickets (mean(sample(…))), and the Monte Carlo is repeating that simulation B B times (replicate). Thought of like that, it almost writes itself.

First, pin down Y Y . Only small prizes and refunds count, so a ticket with a big prize is worth 0 for Y Y : that is why the probability of 0 is 1−0.09986−0.01794=0.8822 1 – 0.09986 – 0.01794 = 0.8822 and the level 1 prob vector is not reused. With these three figures, μ=20⋅0.09986+100⋅0.01794=1.9972+1.794=3.79 \mu = 20 \cdot 0.09986 + 100 \cdot 0.01794 = 1.9972 + 1.794 = 3.79 €: 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 μ=3.79 \mu = 3.79 € (the mean of a mean is the variable’s mean), and the sd column falls with n n just like sd_theory: 14.4 with one ticket, 4.6 with ten, 1.0 with two hundred. Multiplying n n by 100 divides the standard deviation by 100=10 \sqrt{100} = 10 , 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 == 1 would fail for no reason.
  • The anonymous function in sapply. sim_mean returns a list, and sapply needs 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:

PartRouteWhy not the obvious one
a)E[S]=200 μ E[S] = 200\,\mu and σS=σ200 \sigma_S = \sigma\sqrt{200} What adds up are the variances of the 200 independent tickets, not the standard deviations: 200 σ 200\,\sigma would give 2863.36 €
b)sim_mean(200, 5000, …) and multiply the means by 200No need for another simulation: S=200 Yˉ S = 200\,\bar{Y} , 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 2σ/200 2\sigma/\sqrt{200} The inequality is written with Yˉ \bar{Y} ; with tot it also works, but then the distance is 2σ200 2\sigma\sqrt{200}

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, E[S]=200 μ=758.24 E[S] = 200\,\mu = 758.24 € and σS=σ200=202.47 \sigma_S = \sigma\sqrt{200} = 202.47 €: the mean is multiplied by 200, but the standard deviation only by 200≈14.14 \sqrt{200} \approx 14.14 .

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
Density histogram of 5000 syndicates with the CLT normalDensity-scale histogram with breaks every 100 euros from 0 to 1800; the tallest bar is between 700 and 800. On top, the normal curve with mean 758.24 and standard deviation 202.47, which follows the bars well. A vertical line marks 1000 euros.00.00050.0010.00150.002Density0300600900120015001800Total the syndicate wins (euros)dnorm(x, 758.24, 202.47)S ≥ 1000
Redrawn in the site colours: with 200 tickets the sum is already bell-shaped; on the right, the bars stick out slightly above the curve.

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: P(S≥1000) P(S \ge 1000) 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 μ \mu and σ \sigma of Y Y and 1 for moving to S S with 200 \sqrt{200} . 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 σ200 \sigma\sqrt{200} and not 200 σ 200\,\sigma ; 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 ∣Yˉ−μ∣≥2σ/200 \lvert \bar{Y} – \mu \rvert \ge 2\sigma/\sqrt{200} by 200 gives ∣S−200 μ∣≥2σ200 \lvert S – 200\,\mu \rvert \ge 2\sigma\sqrt{200} : 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 1/k2=1/9=0.1111 1/k^2 = 1/9 = 0.1111 . 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")
The same histogram in frequencies and in densityTwo histograms of the same 5000 totals with the same normal curve. Left, in frequencies (up to 986): the curve, 0.002 high, is squashed against the axis. Right, in density: the curve follows the bars.02505007501000Frequency06001200180000.0010.002Density060012001800hist(tot)hist(tot, freq = FALSE)curve flat on the axiscurve over the bars
Without freq = FALSE the curve is there, but it measures thousandths on an axis of hundreds.

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.

Question 1Single choice

What does this code print?

x <- c(4, 0, 2, 6)
cumsum(x) / seq_along(x)
  1. [1] 4 2 2 3
  2. [1] 1 1 1.5 3
  3. [1] 4 4 6 12
  4. [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.

Question 2Single choice

What does the last line print?

r <- list(mean = 3.8, sd = 1.2)
class(r["mean"])
  1. [1] "list"
  2. [1] "numeric"
  3. [1] "character"
  4. 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.

Question 3Short answer

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.

Question 4Single choice

What does the second line do?

hist(rnorm(500), freq = FALSE)
curve(dnorm(x), add = TRUE)
  1. It draws the standard normal density on top of the histogram
  2. It opens a new plot with the curve alone
  3. It gives an error because x is not defined
  4. 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.

Question 5Single choice

How many elements does m have?

m <- replicate(300, mean(sample(1:6, 10, replace = TRUE)))
length(m)
  1. [1] 300
  2. [1] 10
  3. [1] 3000
  4. [1] 1
Solution

Answer: [1] 300

replicate(300, …) evaluates the mean of 10 rolls 300 times and returns the 300 means.

Question 6Single choice

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)
  1. About 2
  2. About 12
  3. About 0.33
  4. About 432
Solution

Answer: About 2

The standard deviation of the mean of n n independent observations is σ/n \sigma/\sqrt{n} : 12 / 6 = 2.

Question 7Single choice

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)
  1. Error: a list cannot be multiplied
  2. Nothing: it prints a number close to 1
  3. Error because list does not accept vectors
  4. return() is missing before list
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”.

Question 8True or false

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)
  1. With k = 2, the bound is 0.25.
  2. If the simulation gives 0.05, Chebyshev holds.
  3. If the simulation gives 0.05, Chebyshev fails because it does not match 0.25.
  4. 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 1/k2 1/k^2 , not that it equals it. With k = 3, the bound is 1/9.

Question 9Single choice

What does this code print?

tot <- c(800, 1200, 950, 1000, 600)
mean(tot >= 1000)
  1. [1] 0.4
  2. [1] 0.2
  3. [1] 2
  4. [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.

Question 10Single choice

What does this code print?

m <- function(n) sqrt(n)
sapply(c(1, 4, 100), m)
  1. [1] 1 2 10
  2. [1] 1 4 100
  3. A list with three elements
  4. [1] 13
Solution

Answer: [1] 1 2 10

sapply(v, f) applies f to each element: 1=1 \sqrt{1} = 1 , 4=2 \sqrt{4} = 2 , 100=10 \sqrt{100} = 10 . It is the factor σ \sigma is divided by in the mean of n n 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:

  1. With n=1 n = 1 , the histogram is flat (a fair die) and the curve looks nothing like it.
  2. With n=5 n = 5 the bell shape already appears; with n=30 n = 30 , the curve fits.
  3. Look at the horizontal axis: narrower each time. The standard deviation of the mean is σ/n \sigma/\sqrt{n} .
  4. Remove freq = FALSE and 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 (μ \mu , σ/n \sigma/\sqrt{n} , the normal). If you return several things, a list. To overlay a curve, a density histogram and curve(…, add = TRUE).

I want to…CodeResult
Simulate a discrete variablesample(v, n, replace = TRUE, prob = p)vector
μ \mu and σ \sigma of a discrete variablesum(v * p), sqrt(sum((v - mu)^2 * p))numbers
Running meancumsum(x) / seq_along(x)vector
See it convergeplot(m, type = "l", log = "x") + abline(h = mu)plot
Means of samplesreplicate(B, mean(sample(…)))B means
Return several thingslist(means = m, mean = mean(m))list
Read an elementr$mean or r[["mean"]]the value
Histogram with a curvehist(x, freq = FALSE) + curve(dnorm(x, mu, s), add = TRUE)bell on top
Simulated proportionmean(tot >= 1000)probability
Chebyshevmean(abs(m - mu) >= k * s) against 1 / k^2frequency ≤ bound

Templates from the exercises: full ticket, μ=10.42 \mu = 10.42 €, σ=1338.75 \sigma = 1338.75 €; small prizes, μ=3.79 \mu = 3.79 €, σ=14.32 \sigma = 14.32 €; syndicate of 200, E[S]=758.24 E[S] = 758.24 €, σS=202.47 \sigma_S = 202.47 €.

SymptomLikely cause
The curve does not show over the histogramFrequency histogram: freq = FALSE is missing
The curve appears in a new plotadd = TRUE is missing in curve
“non-numeric argument to binary operator” with a listr["x"] instead of r[["x"]] or r$x
The running mean never goes downDividing by length(x) instead of seq_along(x)
The simulated mean does not approach μ \mu Heavy tail (rare prizes): it needs an enormous n n

Before you hand it in, ask yourself:

  1. Have I compared the simulated values with the theoretical ones (mean, standard deviation, probability)?
  2. Are my histograms with a curve on the density scale?
  3. Do I read list elements with $ or [[ ]]?
  4. Have I said how many repetitions I did and with which seed?
ME1 exam coming up?The script for every topic, the printable cheat sheet and the pack for each exam, for free.See the pack

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