R intensive 4: limit theorems and sampling — Monte Carlo, functions that return lists and the 8-person lift (and the CLT that gave me 23 % where there was 21 %)

The Monte Carlo method fits in one sentence: if you cannot calculate a probability, simulate the experiment many times and count. The library lift has a sign that says “8 people, 630 kg”, and one afternoon, waiting for it, I wondered how often eight random people would go over the weight. With the central limit theorem I got 23 %. I simulated it out of curiosity and got 21 %. Neither calculation was wrong: the CLT is an approximation, and with 8 people it still shows. Without simulating, I would never have known.

This is the fourth block of the intensive. Inequalities, the law of large numbers, the central limit theorem and sampling distributions are in ME1 topics 7 and 8. Here we program them: simulate the CLT and the law of large numbers, check Chebyshev’s inequality, write functions that return lists, put a curve on top of a histogram and build a Monte Carlo function that works for any experiment.

In a nutshell: the Monte Carlo method estimates a probability by repeating a random experiment B times and computing the proportion of successes, with a standard error of √(p(1 − p)/B). In R you program it with a function that runs the experiment once, replicate (or a matrix with rowSums) to repeat it, and a function that returns a list with the estimate, its error and its interval.

Before you start. You need very little for this block. From R: writing a one-line function, repeating something with replicate, knowing that the mean of a vector of TRUE/FALSE values is a proportion (block 2), and vector recycling (block 3). From statistics, three results from topics 7 and 8 of ME1, which we go over with the lift’s numbers when they come up: the law of large numbers (the mean of many data points approaches the population mean), the central limit theorem (the mean of n data points is almost normal, with standard deviation σ/√n) and Chebyshev’s inequality (a bound on how far a value can fall from the mean, valid for any distribution). The article has three parts, in this order. First, the pieces: estimating a probability by counting, returning the estimate with its error in a list, and checking the three theorems with simulations and charts. Then, the complete lift program written three times: with a loop, with a matrix and with a function that works for any experiment. Finally, how many simulations you need and the typical mistakes. If you get lost, go back to the lift: 8 people, 630 kg and the question of how often they go over.

What you are going to program (and for which topic)

The example: the library lift, with room for 8 people and a 630 kg limit. The weight of a person who gets in is not normal: almost nobody weighs less than 50 kg and there are more people far above the mean than far below. I model it as 50 kg plus a gamma, which has exactly that skewed shape:

# The weight (kg) of a person getting into the lift: 50 + Gamma(shape 3, rate 0.12)
r_weight <- function(n) 50 + rgamma(n, shape = 3, rate = 0.12)
mu <- 50 + 3 / 0.12              # theoretical mean: 75 kg
sigma <- sqrt(3 / 0.12^2)        # theoretical standard deviation
round(c(mu = mu, sigma = sigma), 2)
set.seed(4)
round(r_weight(8), 1)            # one trip: 8 people

Output:

   mu sigma 
75.00 14.43 
[1]  73.8  64.3  63.2  98.0  80.9  57.4  69.4 100.8

r_weight is a one-line function that simulates weights: like rnorm, it takes how many you want. The mean of a Gamma(3, 0.12) is 3 / 0.12 = 25, so the mean weight is 50 + 25 = 75 kg; its variance is 3 / 0.12² = 208.33, and the standard deviation, 14.43 kg. Any trip: eight weights between 57.4 and 100.8 kg.

The question of the block: what is the probability that 8 people weigh more than 630 kg? The sum has mean 8 · 75 = 600 kg, so it takes a somewhat heavy trip. The CLT gives an approximate answer; Monte Carlo, another one; and we are going to see why they do not match.

What you are going to build:

  • The Monte Carlo estimate and a function that returns a list with the estimate, its standard error and its interval.
  • The law of large numbers and the CLT simulated, with overlaid charts (several lines, histogram with a curve).
  • Chebyshev’s inequality checked with data.
  • A general monte_carlo() function that takes the experiment as an argument.

The R pieces you need

Monte Carlo: the probability as the mean of an indicator

We already used it in block 2: the mean of a vector of TRUE/FALSE values is the proportion of TRUEs. Monte Carlo is exactly that, with many repetitions:

# Monte Carlo in one line: the probability as the mean of an indicator
set.seed(10)
trips <- replicate(10000, sum(r_weight(8)))
mean(trips > 630)                # P(the 8 weigh more than 630 kg)

Output:

[1] 0.2111

Ten thousand simulated trips; in 21.11 % of them the sum went over 630 kg. It is an estimate: with another seed it would come out somewhat different. What is missing is knowing how different, and that comes next.

The Monte Carlo line, with five trips

You cannot look at ten thousand trips one by one, but you can look at five. It is the same line, with the same seed and B = 5:

# Monte Carlo with 5 trips, to see it from the inside
set.seed(10)
five <- replicate(5, sum(r_weight(8)))  # 5 trips: 5 sums of 8 weights
round(five, 1)
five > 630                              # does each trip go over?
mean(five > 630)                        # the proportion of trips that go over

Output:

[1] 546.9 620.6 543.0 600.4 684.9
[1] FALSE FALSE FALSE FALSE  TRUE
[1] 0.2

The line is read from the inside out:

PieceWhat it givesWhy
r_weight(8)8 weightsone trip: the 8 people who get in
sum(r_weight(8))one numberthe weight of the trip: 546.9 kg in the first one
replicate(5, …)5 trip weightsrepeats the whole trip 5 times, each time with new people
five > 6305 TRUE/FALSEcompares each trip with the limit: only the fifth, at 684.9 kg, goes over
mean(five > 630)0.2TRUE counts as 1 and FALSE as 0: 1 / 5 = 0.2

With 5 trips, the estimate is 20 %, but if just one trip had come out differently it would be 0 % or 40 %: each trip moves the figure by 20 points. With 10,000, each one moves it by a ten-thousandth, and that is why 0.2111 is already reliable. These five are also the first five of the 10,000 above: same seed and same order.

Check you’ve got it: how would you estimate the probability that the 8 weigh less than 550 kg? Do you have to simulate again?

No. trips already stores the 10,000 trip weights; only the question you ask them changes: mean(trips < 550), which gives 0.1058.

The experiment (8 people getting in) is the same; the only thing that changes is what counts as a success. Simulating again would give another, equally valid estimate, but you would spend time and gain nothing.

Functions that return lists

An estimate without its error is half an answer. The number of successes in B repetitions is a binomial, so the proportion has a standard error of √(p(1 − p)/B). A function that returns a single number cannot give both; one that returns a list can:

# A function that returns a list: estimate, standard error and interval
estimate_prob <- function(success) {
  stopifnot(is.logical(success))
  B <- length(success)
  p <- mean(success)
  se <- sqrt(p * (1 - p) / B)
  list(p = p, se = se, ci95 = p + c(-1, 1) * 1.96 * se, B = B)
}
r <- estimate_prob(trips > 630)
str(r)
round(r$ci95, 4)

Output:

List of 4
 $ p   : num 0.211
 $ se  : num 0.00408
 $ ci95: num [1:2] 0.203 0.219
 $ B   : int 10000
[1] 0.2031 0.2191

str(r) shows the structure of the list: four named elements, each with its type and size. p and se are one number; ci95, two (num [1:2]); B, an integer. That is the advantage of the list: it keeps together things of different sizes and types, and you take them out by name with $.

The arithmetic: √(0.2111 · 0.7889 / 10000) = 0.00408, and the interval is 0.2111 ± 1.96 · 0.00408 = [0.2031, 0.2191]. With 10,000 trips, the probability is almost surely between 20.3 % and 21.9 %.

Where does that square root come from? It is four steps from topic 8, with the lift’s numbers:

StepCalculationWhy
1X = trips that go over, X ~ B(10000, p)each trip goes over or not, with the same probability p, and the trips are independent: it is a binomial
2Var(X) = B · p(1 − p)the variance of the binomial
3Var(X / B) = p(1 − p) / Bthe proportion is X divided by B, and dividing by B divides the variance by B²: B · p(1 − p) / B²
4se = √(0.2111 · 0.7889 / 10000) = 0.00408the square root of that variance; since we do not know p, we plug in its estimate
50.2111 ± 1.96 · 0.00408with a large B, the proportion is almost normal (the CLT again), and ±1.96 standard deviations keep 95 % inside

Notice that B divides inside the square root. That decides how many simulations you need, and you will see it at the end of the article.

Check you’ve got it: with 2500 trips instead of 10,000, what would the standard error be (if the estimate were still 0.2111)?

0.00816, double. B is divided by 4 and it is inside the square root: √4 = 2, so the error is multiplied by 2. The calculation: √(0.2111 · 0.7889 / 2500) = 0.00816.

A quarter of the simulations does not leave you with a quarter of the precision, but with half. And the other way round: to halve the error, you need four times as many trips.

If you are asked for a specific standard error, solve for B: B = p(1 − p) / se². For an error of 0.001 in the lift, 0.2111 · 0.7889 / 0.001² ≈ 166,537 trips. Since you do not know p before simulating, run a short simulation first to get an idea of p, and then work out how many trips you need.

A detail in the code: p + c(-1, 1) * 1.96 * se is the interval in one line thanks to the recycling of block 3. c(-1, 1) * 1.96 * se gives the two margins (one negative and one positive) and adding p centres them.

Use str() every time a function returns something you do not know the shape of (a list, the result of t.test, of hist, of optim…). It tells you what is inside and what each thing is called before you try to take it out.

The law of large numbers: several lines in one chart

The running mean of the weights of the people getting in should approach 75. We simulate three “queues” of 2000 people and compute the running mean of each:

# Law of large numbers: the running mean of the weights approaches 75
set.seed(12)
paths <- replicate(3, cumsum(r_weight(2000)) / (1:2000))
round(paths[c(10, 100, 2000), ], 2)

Output:

      [,1]  [,2]  [,3]
[1,] 69.34 78.77 78.45
[2,] 73.52 77.84 73.32
[3,] 75.78 74.97 75.53

Here replicate does something new: since each repetition returns a vector of 2000 means, it puts the three together as a matrix with 2000 rows and 3 columns (one column per path). After 10 people, the three paths are at 69.34, 78.77 and 78.45 kg: far from each other and from 75. After 2000, at 75.78, 74.97 and 75.53: almost together.

The running mean, person by person

cumsum(r_weight(2000)) / (1:2000) does two things in one line. With 4 people and the same seed you can see both:

# The running mean with 4 people, step by step
set.seed(12)
x4 <- r_weight(4)
round(x4, 2)                    # the weights, in order of arrival
round(cumsum(x4), 2)            # what they add up to so far
round(cumsum(x4) / (1:4), 2)    # divided by how many people there are so far

Output:

[1] 55.89 63.52 99.53 67.03
[1]  55.89 119.41 218.95 285.98
[1] 55.89 59.71 72.98 71.49
PersonWeightcumsumDivided byRunning meanWhy
155.8955.89155.89with a single person, the mean is their weight
263.52119.41259.7155.89 + 63.52, divided by 2
399.53218.95372.98one heavy person pushes the mean up 13 kg in one go
467.03285.98471.49the fourth brings it down, but less: they are already 1 of 4

cumsum gives what has been added up after each person, and 1:4, how many people there are so far. The division goes element by element, as in block 3: the sum in position i divided by i. These four means are the first four rows of the first path (the 55.89 is the 56 kg person in the drawing).

And look at how much each new person weighs in. The third moves the mean by 13 kg; person 2000 would move it by a few grams, because they count as 1 of 2000. That is why the paths settle down: not because the weights stop varying, but because each one counts for less and less.

matplot draws one line per column of a matrix in one go:

matplot(paths, type = "l", lty = 1, log = "x", col = c("#5B4BDB", "#FF6B4A", "#16794B"),
        main = "The running mean of the weights", xlab = "People", ylab = "Mean (kg)")
abline(h = mu, lty = 2)
Three paths of the running meanThree coloured lines with the running mean of the weights from 1 to 2000 people, on a log scale. They start at 55.9, 61.4 and 95.5 kg and end at 75.78, 74.97 and 75.53, around the dashed line at 75.5060708090100People (log scale)Mean (kg)The running mean of the weights1101001,0002,000μ = 75
Far apart at first, the three paths close in on 75 kg: the law of large numbers.

In the drawing, the three paths start very far apart (the first person can weigh 56 kg or 96) and close in on the dashed 75 kg line. That is the law of large numbers: the sample mean approaches the population mean. And the logarithmic scale on the horizontal axis (log = "x") is again what lets you see the first people and the 2000 at the same time.

The CLT simulated: a histogram with a curve on top

The CLT says that the mean of n weights is approximately normal, with mean 75 and standard deviation σ/√n. Let us check it with n = 1 (a single weight) and n = 8 (a trip):

# The CLT simulated: means of n weights, against the normal the theorem predicts
means_of <- function(n, B = 10000) replicate(B, mean(r_weight(n)))
set.seed(20)
m1 <- means_of(1)
m8 <- means_of(8)
round(c(sd_m8 = sd(m8), sd_clt = sigma / sqrt(8)), 3)

Output:

 sd_m8 sd_clt 
 5.060  5.103 

The standard deviation of the 10,000 means of 8 is 5.060, and the CLT predicts 14.43 / √8 = 5.103. They match: that is not approximate, it is exact for any distribution (the variance of a mean is always σ²/n). What the CLT adds is the shape, and you can only see that by drawing:

par(mfrow = c(1, 2))
hist(m1, breaks = 40, freq = FALSE, main = "n = 1", xlab = "kg", col = "#A99EF5", border = "white")
curve(dnorm(x, mean = mu, sd = sigma), add = TRUE, col = "#FF6B4A", lwd = 2)
hist(m8, breaks = 40, freq = FALSE, main = "n = 8", xlab = "kg", col = "#A99EF5", border = "white")
curve(dnorm(x, mean = mu, sd = sigma / sqrt(8)), add = TRUE, col = "#FF6B4A", lwd = 2)
par(mfrow = c(1, 1))
The CLT simulated: means of 1 and of 8 weightsTwo density histograms with their normal in coral. With n = 1 the histogram starts at 50 kg and has a long right tail; the normal does not fit. With n = 8 the histogram is almost a bell centred on 75 and the normal with standard deviation 14.43/√8 fits quite well.n = 150100150kgn = 86080100kgthe normal spillsover the left
From a single weight to the mean of a trip: the skew almost disappears and the bell shows up.

The two panels of the drawing tell the CLT better than any formula. With n = 1, the histogram is that of a single weight: it starts abruptly at 50 kg and has a long tail to the right; the normal (in coral) does not fit at all, it spills over the left where there is nobody. With n = 8, the histogram is already almost a bell and the curve fits it quite well, although it still has a hint of a tail on the right.

Four pieces of code that make this possible:

  • par(mfrow = c(1, 2)) splits the chart window into 1 row and 2 columns; each hist takes the next one. At the end, par(mfrow = c(1, 1)) leaves it as it was (otherwise the next chart would come out at half size).
  • freq = FALSE puts the histogram on the density scale, the only scale on which it can be compared with a density curve.
  • curve(expression in x, add = TRUE) draws a function of x on top of the open chart. Without add = TRUE it would open a new chart and the histogram would disappear.
  • breaks = 40 asks R for about 40 classes (it is a suggestion: R picks nearby round breaks).

Where σ/√n comes from (and what the CLT adds)

There are two different claims in this section, and it is worth separating them. The first is exact: the mean of n weights has mean μ and standard deviation σ/√n, whatever the distribution. The second is the CLT’s: its shape looks like the normal, and more so the larger n is. The first comes out in four steps:

StepCalculation with n = 8Why
1Var(one weight) = σ² = 208.333 / 0.12², the variance of the gamma; adding 50 kg does not change the variance
2Var(sum of 8) = 8 · 208.33 = 1666.67the people are independent: variances add up
3Var(mean of 8) = 1666.67 / 64 = 26.04the mean is the sum divided by 8, and dividing by 8 divides the variance by 8² = 64
4standard deviation = √26.04 = 5.103it is 14.43 / √8: σ/√n

None of this needs the normal, only independence. That is why the simulated 5.060 and the theoretical 5.103 match even with such a skewed weight. What the CLT says is a separate thing, and it is what the drawing shows: the bell. And it is approximate: with n = 8 there is still that hint of a tail, and that will have consequences in version 3.

Dividing by n instead of by √n. The standard deviation of the mean of 8 weights is 14.43 / √8 = 5.10 kg, not 14.43 / 8 = 1.80. What gets divided by n is the variance (208.33 / 8 = 26.04); when you take the square root, the n becomes √n.

Check you’ve got it: what standard deviation would the mean of 32 weights have? And what shape do you expect in its histogram?

14.43 / √32 = 2.55 kg: half of what it is with 8, because 32 is 8 · 4 and √4 = 2. That is exact; it does not depend on the shape of the weight.

The shape, by the CLT, even closer to the bell than with 8: the tail on the right would barely show. To check it, m32 <- means_of(32) and the same hist, with sd = sigma / sqrt(32) in the curve, would be enough.

Chebyshev checked by simulation

Chebyshev says that, for any distribution, P(|X − μ| ≥ kσ) ≤ 1/k². With sapply we compute the simulated probability for three values of k:

# Chebyshev checked: P(|X - mu| >= k sigma) against its bound 1/k^2
set.seed(30)
x <- r_weight(100000)
k <- c(1.5, 2, 3)
simulated <- sapply(k, function(kk) mean(abs(x - mu) >= kk * sigma))
round(rbind(k, simulated, bound = 1 / k^2), 4)

Output:

            [,1]   [,2]   [,3]
k         1.5000 2.0000 3.0000
simulated 0.0915 0.0438 0.0113
bound     0.4444 0.2500 0.1111

The three simulated probabilities are well below their bounds: 0.0915 against 0.4444, 0.0438 against 0.25 and 0.0113 against 0.1111. Chebyshev holds, but it is very conservative: since it works for any distribution, it has to cover the worst case. The anonymous function function(kk) … uses the name kk so as not to clash with the vector k outside (it would work with k too, because the argument wins inside, but reading it would be a mess).

Read in words, the inequality says: the probability of being k standard deviations or more away from the mean is at most 1/k². Translated into kilos, with μ = 75 and σ = 14.43:

kkσ“Far” means…BoundSimulatedWhy
1.521.65 kgbelow 53.35 or above 96.650.44440.09151 / 1.5² = 1 / 2.25; the simulated value adds both tails: 0.0084 below and 0.0831 above
228.87 kgbelow 46.13 or above 103.870.250.0438there is nobody below 46.13 (the minimum is 50): all the probability is in the right tail
343.30 kgbelow 31.70 or above 118.300.11110.0113again only the right tail: just over 1 person in 100 weighs more than 118.30 kg

The table explains why the bound is so far off. Chebyshev knows nothing about the weight: it also has to hold for distributions with a lot of probability at the extremes, so it assumes the worst. The lift does not even have a left tail. It is a bound for when you do not know the distribution, not a way of computing the probability.

TheoremWhat it saysHow to program it
Law of large numbersthe sample mean approaches μcumsum(x) / seq_along(x) and matplot
CLTthe mean of n is almost normal, with standard deviation σ/√nreplicate(B, mean(r(n))), hist(freq = FALSE) + curve(add = TRUE)
ChebyshevP(|X − μ| ≥ kσ) ≤ 1/k²mean(abs(x - mu) >= k * sigma) against 1 / k^2

The complete program: the lift, three times

Back to the opening question, P(the 8 weigh more than 630 kg), to write the program the way it would really be written: first something that works, then something fast, finally something that works for any question.

Version 1: a loop that counts

# Version 1: count trips with a loop
set.seed(10)
over <- 0
for (b in 1:10000) {
  if (sum(r_weight(8)) > 630) over <- over + 1
}
over / 10000

Output:

[1] 0.2111

The same 0.2111 as with replicate: same seed and same order of the random numbers (8 weights per trip, trip after trip). It is the most direct way to think about it: a counter that goes up every time the trip is over.

Version 2: all the trips in a matrix

In block 3 we saw that asking for numbers one at a time is slow. Here we ask for the 80,000 weights in one go and place them in a matrix with one row per trip:

# Version 2: the 10,000 trips at once, in a matrix
set.seed(10)
weights <- matrix(r_weight(10000 * 8), ncol = 8)   # one row per trip
dim(weights)
mean(rowSums(weights) > 630)

Output:

[1] 10000     8
[1] 0.216

rowSums adds up each row (the weight of each trip) in compiled code, and mean(… > 630) does the rest. It comes out as 0.216 and not 0.2111: with the same seed, matrix hands out the numbers by columns (the first 10,000 go to the first person of each trip), so the trips are different ones. Both estimates are equally good; the difference, 0.005, is within what the standard error says (0.004 each).

The matrix of 10,000 tripsSketch of the weights matrix: 10,000 rows (trips) and 8 columns (people). Each row is summed with rowSums and compared with 630, giving TRUE or FALSE; the mean of those 10,000 logical values is 0.216. The weights shown are illustrative.One row per trip, one column per personp1p2p3p4p5p6p7p873.864.363.298.080.957.469.4100.8607.8FALSE81.270.466.992.377.588.172.085.6634.0TRUE⋮69.574.158.879.066.271.790.463.3573.0FALSErowSums> 6301210,000mean(rowSums(weights) > 630) → 0.216
rowSums turns each row into the weight of a trip; the comparison, into a TRUE or a FALSE (example weights).

The drawing shows the matrix: 10,000 rows, one per trip; 8 columns, one per person. rowSums turns it into 10,000 trip weights and the comparison with 630, into 10,000 TRUE/FALSE values.

By columns or by rows: why it comes out as 0.216

That matrix hands out the numbers by columns is easy to see with six numbers in two columns:

# How matrix fills in: by columns (the default) or by rows
matrix(1:6, ncol = 2)
matrix(1:6, ncol = 2, byrow = TRUE)

Output:

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6

By default, R fills the first column from top to bottom (1, 2, 3) and then the second (4, 5, 6). With byrow = TRUE it fills the first row (1, 2) and then the next. In the lift, each row is a trip. By columns, row 1 gets weight number 1, number 10,001, number 20,001…: people who were in different trips in version 1. The trips are different ones, and that is why the estimate is different. It is not a mistake: the 80,000 weights are just as random however they are distributed.

Check you’ve got it: if you add byrow = TRUE in version 2, what estimate comes out with the same seed?

0.2111, the same as version 1. With byrow = TRUE, row 1 gets the first 8 weights, row 2 the next 8…, which is exactly the order in which the loop asked for the people of each trip. Same trips, same count.

I checked it: after set.seed(10), mean(rowSums(matrix(r_weight(80000), ncol = 8, byrow = TRUE)) > 630) gives 0.2111.

Version 3: a general Monte Carlo function

The last idea is the most powerful of the block: a function that takes another function as an argument. That way, the same code works for the lift with 8, with 9 or any other experiment:

# Version 3: a general function that takes the experiment as an argument
monte_carlo <- function(experiment, B = 10000, seed = NULL) {
  stopifnot(is.function(experiment), B >= 100)
  if (!is.null(seed)) set.seed(seed)
  success <- replicate(B, experiment())
  estimate_prob(success)
}
lift <- function(n = 8, limit = 630) sum(r_weight(n)) > limit
r8 <- monte_carlo(lift, seed = 10)
r9 <- monte_carlo(function() lift(n = 9, limit = 700), seed = 10)
round(c(p8 = r8$p, p9 = r9$p), 4)
round(c(clt8 = 1 - pnorm(630, 8 * mu, sqrt(8) * sigma),
        clt9 = 1 - pnorm(700, 9 * mu, sqrt(9) * sigma)), 4)

Output:

    p8     p9 
0.2111 0.2605 
  clt8   clt9 
0.2312 0.2819 

How it works inside:

  1. experiment is a function with no arguments that runs the experiment once and returns TRUE or FALSE. monte_carlo calls it with experiment() inside replicate.
  2. lift is that experiment, with default values for 8 people and 630 kg. It is passed without parentheses (monte_carlo(lift)): you give it the recipe, not the result.
  3. For another lift (9 people, 700 kg) you wrap the call in an anonymous function: function() lift(n = 9, limit = 700).
  4. seed = NULL by default: if you do not give it, it is not fixed (the usual randomness); if you give it, the result can be repeated. is.null checks which of the two cases it is.
  5. The result is the list from estimate_prob, with its standard error included.

One call, step by step

Passing a function to another function is the hardest part of this block. This is what monte_carlo(lift, seed = 10) does inside:

StepWhat happensWhy
1experiment becomes liftit was passed without brackets: monte_carlo receives the whole function, not a TRUE or a FALSE
2stopifnot(…) does not complainlift is a function and B is 10,000 by default, more than 100
3set.seed(10)seed is not NULL, so it is set: that is why the same 0.2111 as in version 1 comes out
4replicate(10000, experiment())each round calls lift() with its default values (8 people, 630 kg): it adds up 8 weights and compares; out come 10,000 TRUE/FALSE
5estimate_prob(success)the function from before turns those TRUE/FALSE values into the list with p, se, ci95 and B

For the lift with 9, the key is step 4: replicate calls experiment() with no arguments, so there is no way to pass it n = 9 from outside. That is why you wrap it: function() lift(n = 9, limit = 700) is a function with no arguments that, when called, calls lift with the values you have fixed.

Writing monte_carlo(lift(), seed = 10), with brackets. lift() runs once before going in, and monte_carlo receives a single TRUE or FALSE instead of a function. The stopifnot stops it with “is.function(experiment) is not TRUE”: if you see that message, look for an extra pair of brackets.

And now the comparison from the beginning. For 8 people, Monte Carlo gives 0.2111 and the CLT, 0.2312 (the sum, approximated by a normal with mean 600 and standard deviation √8 · 14.43 = 40.82). For 9 people and 700 kg, 0.2605 against 0.2819. The CLT overshoots in both cases, by about two points. Why? Because the sum of 8 or 9 weights is still somewhat skewed (you saw it in the n = 8 histogram): its median is below its mean, and above 630 kg there is a little less than the symmetric bell gives it. With 30 or 40 people the difference would disappear.

The two CLT figures, step by step:

Step8 people, 630 kg9 people, 700 kgWhy
Mean of the sum8 · 75 = 6009 · 75 = 675means add up
Standard deviation of the sum√8 · 14.43 = 40.82√9 · 14.43 = 43.30variances add up (n · σ²), and the square root gives √n · σ
Standardise(630 − 600) / 40.82 = 0.7348(700 − 675) / 43.30 = 0.5774how many standard deviations the limit is above the mean
Right tail1 − Φ(0.7348) = 0.23121 − Φ(0.5774) = 0.2819pnorm gives the area on the left; going over is the area on the right

If you round z to 0.73 and 0.58 and look it up in the normal table, you get 0.2327 and 0.2810: almost the same, but not the figures in the code, which use the unrounded z. Subtracting, the CLT overshoots by 0.0201 with 8 people and by 0.0214 with 9: the “about two points”. And it is not simulation noise: 0.0201 is about five standard errors (0.0041), and 0.2312 falls well outside the Monte Carlo interval [0.2031, 0.2191].

Trusting the CLT with a small n and a very skewed population. With n = 8 it is a reasonable approximation for quick calculations, not an exact result. When in doubt, Monte Carlo tells you how wrong it is.

How many simulations do you need?

The standard error is √(p(1 − p)/B): to divide it by 10 you have to multiply B by 100. Checked:

# How many simulations do you need? The standard error falls like 1/sqrt(B)
set.seed(40)
B <- c(100, 1000, 10000, 100000)
sapply(B, function(b) round(monte_carlo(lift, B = b)$se, 4))

Output:

[1] 0.0400 0.0134 0.0041 0.0013
How the Monte Carlo error fallsHorizontal bars of the standard error for 100, 1000, 10,000 and 100,000 simulations: 0.04, 0.0134, 0.0041 and 0.0013, with their 95 % margin in percentage points.Standard error of the estimate by number of simulationsB = 1000.04 (± 7.8 points)B = 1,0000.0134 (± 2.6 points)B = 10,0000.0041 (± 0.8 points)B = 100,0000.0013 (± 0.3 points)B × 10 → error ÷ √10 ≈ 3.16
To divide the error by 10 you have to multiply the simulations by 100.

Every time B is multiplied by 10, the error is divided by roughly 3.16 (which is √10): 0.04, 0.0134, 0.0041 and 0.0013. As the drawing shows, with 100 simulations the standard error is 4 points (and the 95 % margin almost ±8: useless for telling 21 % from 23 %); with 10,000, 0.4 points (±0.8). That is why almost all the examples use 10,000: it is the point where the error is already small and the simulation is still quick.

Common mistakes (with R’s real message)

Operating on a list element taken out with a single bracket.

r8[1] * 100

Output:

Error in r8[1] * 100 : non-numeric argument to binary operator

“non-numeric argument to binary operator”: r8[1] is not the number, it is a one-element list that contains the number. To get the content: r8[[1]] * 100 or, better, r8$p * 100. Rule: [ ] returns a piece of the same type (a smaller list); [[ ]] and $ take out what is inside.

Asking for an element that does not exist.

r8$probability

Output:

NULL

NULL, with no error or warning: the list has no element called probability (it is called p). It is dangerous because NULL spreads silently (NULL * 100 gives an empty vector, numeric(0)). If in doubt, names(r8) or str(r8).

rowSums on a vector.

rowSums(r_weight(8))

Output:

Error in rowSums(r_peso(8)) : 'x' must be an array of at least two dimensions

“‘x’ must be an array of at least two dimensions”: rowSums needs a matrix (rows and columns) and a vector has no rows. If it happens with something you thought was a matrix, look at dim(x): if it gives NULL, it is a vector. It happens, for example, when a matrix ends up with a single row after filtering (use drop = FALSE when filtering).

mean of a list.

mean(list(70, 80, 75))

Output:

[1] NA
Warning message:
In mean.default(list(70, 80, 75)) :
  argument is not numeric or logical: returning NA

It returns NA with the warning “argument is not numeric or logical: returning NA”. A list is not a vector of numbers, even if it only holds numbers. It happens when sapply cannot simplify and returns a list; convert it first with unlist(): mean(unlist(list(70, 80, 75))) gives 75.

Forgetting add = TRUE in curve() (or in hist when you want to overlay; lines and points do not need it). There is no error: the curve appears on its own in a new chart and the histogram that was underneath can no longer be seen.

Try it in the R playground

Copy the script into the R playground on the site and run it.

r_weight <- function(n) 50 + rgamma(n, shape = 3, rate = 0.12)
mu <- 75; sigma <- sqrt(3 / 0.12^2)

monte_carlo <- function(experiment, B = 10000) {
  success <- replicate(B, experiment())
  p <- mean(success)
  list(p = p, se = sqrt(p * (1 - p) / B))
}
lift <- function(n = 8, limit = 630) sum(r_weight(n)) > limit

set.seed(10)
str(monte_carlo(lift))
1 - pnorm(630, 8 * mu, sqrt(8) * sigma)        # what the CLT says

m30 <- replicate(10000, mean(r_weight(30)))
hist(m30, breaks = 40, freq = FALSE, main = "Means of 30 weights", xlab = "kg")
curve(dnorm(x, mu, sigma / sqrt(30)), add = TRUE, col = "#FF6B4A", lwd = 2)

What to look at:

  1. In the console, str shows the list with p and se. Compare p with what the CLT says.
  2. Look at the histogram of the means of 30 weights: does the curve fit better than with 8?
  3. Try a lift for 30 people with a 2350 kg limit (mean 2250): monte_carlo(function() lift(30, 2350)) against 1 - pnorm(2350, 30 * mu, sqrt(30) * sigma). Are they closer than with 8?
  4. Remove add = TRUE from curve and run the last two lines again: what happened to the histogram?

Summary

PieceWhat forExample from the article
mean(replicate(B, exp()))estimate a probability (Monte Carlo)P(> 630 kg) = 0.2111
list(a = …, b = …) and str()return several things and see what is insideestimate_prob()
[[ ]] and $ against [ ]take out the content against a piece of a listr8$p, not r8[1]
matrix(…, ncol = n) + rowSumsmany repetitions at once10,000 trips, 0.216
Functions as argumentsone piece of code for any experimentmonte_carlo(lift)
matplot, curve(add = TRUE), par(mfrow)overlaid charts and panelsthe LLN and the CLT
Standard error √(p(1 − p)/B)knowing how much to trust it0.04 with 100, 0.0013 with 100,000

Three ideas to take with you:

  1. A Monte Carlo estimate without its standard error says nothing. Return them together, in a list.
  2. Separate the experiment from the repetition. One function runs the experiment once; another (monte_carlo) repeats and summarises it. That way you change the experiment without touching the rest.
  3. Simulating tells you when to trust a theorem. The CLT with 8 skewed weights is off by two points; you only know if you compare.

What next?

In the R intensive 4 exercises you will program your own simulations of the CLT and Chebyshev, functions that return lists and Monte Carlo estimates with their error, with the cheat sheet for the block.

And to close the intensive, block 5: estimation and intervals, where optimize and optim find the maximum likelihood for you, we simulate the coverage of an interval and organise the exam script.

Did this article help you? Here is how you can support SergioLearns →

Next step: exercisesR 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)Next block: optimize, optim, intervals and the exam scriptR intensive 5: estimation and intervalsCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script