R intensive 3: normal and joint distributions — vectorising, pnorm in your functions and simulating my 5 km and 10 km runs (and the loop that took 40 times longer)
In R, the fastest loop is the one you do not write. I learnt it with a 200,000-race simulation for a lab: my version with for and if took two and a half seconds, and a classmate’s, which did exactly the same thing without a loop, took less than a tenth. He was not cleverer: he had let R work with the whole vector, which is what it is built for.
This is the third block of the intensive. The normal distribution, transformations and joint distributions are in ME1 topics 5 and 6; here we learn to program them: operate on whole vectors, ifelse, apply and sapply, use rnorm, pnorm and qnorm inside your functions, simulate transformations and joint variables, and measure how long each version takes with system.time.
In a nutshell: vectorising in R means writing the operation for the whole vector (t5 / 5, ifelse(t5 < 26, …), rnorm(n, …)) instead of walking through it element by element with a loop. It is shorter, it makes fewer mistakes and, in large simulations, it is dozens of times faster; apply and sapply cover what is not vectorised out of the box.
Table of Contents
Before you start. You need very little for this block. From R: creating vectors with c(), picking elements with [ ], writing your own function and a for loop with an if inside (you have all of it in R from scratch and in the first two blocks of the intensive). From statistics: that a normal is described by its mean and its standard deviation, what pnorm and qnorm answer (topic 5) and what the covariance and the correlation of two variables measure (topic 6). You do not need to remember the formulas: when they come up, we go over them with their numbers. The article has three parts, in this order. First, the pieces: operating on a whole vector, deciding with ifelse, going through a matrix with apply and through a list of values with sapply, and putting the normal inside your functions. Then, the complete program: the 5 and 10 km season written twice, with a loop and vectorised, and the stopwatch to see how much you gain. Finally, what topic 6 says about the two races together, checked with the simulation. If you get lost, go back to the 8 times in t5: the whole article is doing sums with them without going one by one.
What you are going to program (and for which topic)
The example for this block: my running times. I run 5 km races and, now and then, 10 km ones. My 5 km time looks like a normal with mean 26 minutes and standard deviation 1.5; and my 10 km time depends a lot on the 5 km one (if I am in good shape that day, I am good in both): roughly double plus one minute, with its own noise. Those are two joint, correlated variables, exactly what topic 6 is about.
What you are going to build:
- Calculations on whole vectors, without loops: paces, deviations, classifications with
ifelse. - Summaries by rows and columns of a matrix with
apply, and functions applied to lists of values withsapply. - A function that uses
pnormandqnormto answer questions about your times. - The simulation of a transformation (from time to speed) and of a season of 5 and 10 km races, first with a loop and then vectorised, with its covariance, its correlation and its scatter plot.
The hand calculations for the normal and joint distributions are in the R practice of topics 5 and 6. Here, the code.
The R pieces you need
Operating on the whole vector
In R almost everything works element by element without you asking. If you divide a vector by 5, each element is divided:
# My times (in minutes) in the 8 races of 5 km this season t5 <- c(27.4, 26.1, 25.8, 26.9, 24.9, 25.6, 26.3, 25.2) t5 / 5 # pace in min/km: each time divided by 5, no loop t5 - mean(t5) # how far each race is from the mean sum(t5 < 26) # how many are under 26 minutes
Output:
[1] 5.48 5.22 5.16 5.38 4.98 5.12 5.26 5.04 [1] 1.375 0.075 -0.225 0.875 -1.125 -0.425 0.275 -0.825 [1] 4
Three lines, three operations on the 8 times at once:
t5 / 5gives the pace of each race: 27.4 / 5 = 5.48 minutes per kilometre in the first one.t5 - mean(t5): the mean is 26.025, so the first race is 27.4 − 26.025 = 1.375 minutes above. Notice thatmean(t5)is a single number and it is subtracted from each element.sum(t5 < 26):t5 < 26is a vector of 8TRUE/FALSEvalues, andsumcounts theTRUEs: 4 races under 26 minutes (the 25.8, 24.9, 25.6 and 25.2 ones).
That is vectorising: writing the operation for the vector, not for each element.
The drawing compares the two ways of thinking: with a loop, you go cell by cell and decide what to do in each one; vectorising, you give R the operation and it applies it to all of them inside (in compiled code, which is much faster than the R you write).
The same calculation, with and without a loop
To convince yourself that vectorising is not magic, write the pace the way you would in Python or Java and compare it with the one-line version:
# The pace with a loop, as in Python or Java
pace <- numeric(length(t5)) # I reserve the 8 cells first
for (i in seq_along(t5)) {
pace[i] <- t5[i] / 5 # one cell on each pass
}
identical(pace, t5 / 5) # is it exactly the same as the vectorised one?
t5 < 26 # the comparison also goes element by element
mean(t5 < 26) # the mean of TRUE/FALSE is a proportion
Output:
[1] TRUE [1] FALSE FALSE TRUE FALSE TRUE TRUE FALSE TRUE [1] 0.5
| Line | Result | Why |
|---|---|---|
identical(pace, t5 / 5) | TRUE | both versions give the same 8 numbers, without a single difference: the only thing that changes is who goes through the vector |
t5 < 26 | 8 TRUE/FALSE | it compares each time with 26, just as / divided each one by 5 |
mean(t5 < 26) | 0.5 | R counts TRUE as 1 and FALSE as 0: 4 ones out of 8 values is 4 / 8 = 0.5 |
The loop needs three things the vectorised version does not: reserving the vector first (numeric(length(t5))), an index i that moves forward and writing into pace[i]. Each one is a place to make a mistake (a 1:9 instead of seq_along(t5), for example). The vectorised version has no index to get wrong.
And the last line is a trick you will use all the time: sum of a condition counts how many times it holds and mean tells you in what proportion. Half of my races this season are under 26 minutes.
ifelse and recycling
The normal if only looks at one value. To decide something for each element of a vector there is ifelse(condition, if_yes, if_no):
# ifelse: one if for each element, in one go ifelse(t5 < 26, "good", "normal") # Recycling: the short vector repeats to fit the long one t5[1:4] - c(0, 1)
Output:
[1] "normal" "normal" "good" "normal" "good" "good" "normal" [8] "good" [1] 27.4 25.1 25.8 25.9
ifelse returns a vector as long as the condition: “good” in the 4 races under 26 minutes and “normal” in the others.
The second line shows something that is sometimes useful and sometimes a trap: recycling. t5[1:4] has 4 elements and c(0, 1) has 2, so R repeats the short one (0, 1, 0, 1) and subtracts: 27.4 − 0, 26.1 − 1, 25.8 − 0, 26.9 − 1. It is the same thing that happens with t5 - mean(t5): a single number is a vector of length 1 that gets recycled.
Recycling, position by position
t5[1:4] - c(0, 1) is easier to understand written in columns. R stretches the short vector by repeating it until it is as long as the long one, and then subtracts cell by cell:
| Position | t5[1:4] | Short vector, recycled | Result | Why |
|---|---|---|---|---|
| 1 | 27.4 | 0 | 27.4 | first element of c(0, 1) |
| 2 | 26.1 | 1 | 25.1 | second element |
| 3 | 25.8 | 0 | 25.8 | the short vector has run out: it starts again from the 0 |
| 4 | 26.9 | 1 | 25.9 | and the 1 again; 4 is a multiple of 2, so it fits exactly |
With t5 - mean(t5) the same thing happens, but the short vector has a single element, 26.025, and it is repeated 8 times. That is why you never see it as recycling: subtracting a number from a vector looks natural. It is the most useful case and the one you will use all the time; the one with two or more elements, only when you really want it (for example, to alternate).
Check you’ve got it: what does t5 - c(0, 1) do with the 8 races? Does it give a warning?
It subtracts 0, 1, 0, 1… along the 8 and you get 27.4 25.1 25.8 25.9 24.9 24.6 26.3 24.2: the odd races stay the same and the even ones lose a minute.
It gives no warning, because 8 is a multiple of 2 and the short vector fits in whole 4 times. The warning in the common mistakes appears when it does not fit: 3 elements minus 2 leaves the last round half done. And careful: no warning does not mean it is what you wanted. R only checks that the lengths fit, not that subtracting like that makes sense.
R functions that are already vectorised
The distribution functions also accept vectors in any of their arguments:
# Many R functions are already vectorised: pnorm with three standard deviations at once pnorm(25, mean = 26, sd = c(1, 1.5, 2))
Output:
[1] 0.1586553 0.2524925 0.3085375
Three probabilities of going under 25 minutes in one line: 0.159 if I were very consistent (standard deviation 1), 0.252 with my standard deviation of 1.5 and 0.309 if I were very inconsistent (standard deviation 2). Why does it go up? The more inconsistent you are, the more likely it is that one day you run a very good race (and a very bad one too). Before writing a loop, check whether the function already accepts a vector: it almost always does.
Matrices with apply
With a matrix, apply(M, margin, f) applies f to each row (margin = 1) or each column (margin = 2):
# Matrices: 4 weeks (rows) x 3 training sessions (columns), in minutes for 5 km
M <- matrix(c(27.9, 27.2, 26.8, 26.5,
27.1, 26.9, 26.2, 25.9,
28.3, 27.6, 27.0, 26.4), nrow = 4,
dimnames = list(paste0("wk", 1:4), c("Mon", "Wed", "Fri")))
M
apply(M, 1, mean) # 1 = by rows: the mean of each week
apply(M, 2, min) # 2 = by columns: the best time on each day
Output:
Mon Wed Fri
wk1 27.9 27.1 28.3
wk2 27.2 26.9 27.6
wk3 26.8 26.2 27.0
wk4 26.5 25.9 26.4
wk1 wk2 wk3 wk4
27.76667 27.23333 26.66667 26.26667
Mon Wed Fri
26.5 25.9 26.4
matrix fills by columns: the first 4 numbers are the Monday column, the next 4 the Wednesday one and the last ones the Friday one. dimnames names the rows and columns, which is why the output says wk1 and Mon.
The weekly means go down from 27.77 to 26.27: the training works. And the best time of each day of the week comes from Wednesday (25.9). Let us check one by hand: week 1 is (27.9 + 27.1 + 28.3) / 3 = 83.3 / 3 = 27.7667.
For the most common calculations there are shortcuts that are already vectorised and faster: rowMeans(M), colMeans(M), rowSums(M) and colSums(M). apply is for any other function (the minimum, the maximum, one of yours).
apply, row by row
What apply(M, 1, mean) does is the same thing you would do by hand: take a row, work out its mean and write it down. Four rows, four sums:
| Row | Values (Mon; Wed; Fri) | Sum | Mean | Why |
|---|---|---|---|---|
| wk1 | 27.9; 27.1; 28.3 | 83.3 / 3 | 27.77 | margin 1: apply gives mean the whole row, the three days of the week |
| wk2 | 27.2; 26.9; 27.6 | 81.7 / 3 | 27.23 | next row, same function |
| wk3 | 26.8; 26.2; 27.0 | 80.0 / 3 | 26.67 | Friday already drops from 28 to 27: the improvement shows |
| wk4 | 26.5; 25.9; 26.4 | 78.8 / 3 | 26.27 | the last one; apply puts the 4 means together in a vector with the row names |
The sums (83.3, 81.7, 80.0 and 78.8) are exactly what rowSums(M) gives, and dividing them by 3 is rowMeans(M): that is why the shortcut exists.
Mixing up the margin. If you want the best time on each day and write apply(M, 1, min), R does not complain: it returns 27.1 26.9 26.2 25.9, the best time of each week. That is four numbers instead of three and they carry the names wk1…wk4: look at the names in the output and you will know what you have gone through. To remember it, in M[i, j] the row comes first, and the 1 in apply is that first position.
sapply with an anonymous function
sapply(vector, f) applies f to each element and puts the results together. With an anonymous function you write the f in the call itself:
# sapply: apply a function to each element and combine the results targets <- c(24, 25, 26, 27) sapply(targets, function(o) round(pnorm(o, mean = 26, sd = 1.5), 3))
Output:
[1] 0.091 0.252 0.500 0.748
The probability of going under each target: under 24 minutes, only 9.1 %; under 26 (my mean), exactly 50 %, as it has to be in a normal. Here sapply was not needed, because pnorm(targets, 26, 1.5) is already vectorised; but the pattern sapply(values, function(v) …) works for any function that is not, like the ones you write with an if inside.
When you really need sapply
The example above did not need sapply. This one does: a function with an if inside, which can only look at one number at a time.
# A function with if: it can only look at one time at a time
classify <- function(t) {
if (t < 26) "good" else "normal"
}
classify(25.2) # with a single number it works
sapply(t5, classify) # sapply passes it each race
Output:
[1] "good" [1] "normal" "normal" "good" "normal" "good" "good" "normal" "good"
| Call | Result | Why |
|---|---|---|
classify(25.2) | “good” | a single number: the if gets a single TRUE and decides |
classify(t5) (not in the code) | error | the if would get 8 TRUE/FALSE values: it is the “the condition has length > 1” from the common mistakes |
sapply(t5, classify) | 8 labels | sapply calls classify 8 times, once with each time, and puts the answers together in a vector |
You get the same as with ifelse(t5 < 26, "good", "normal"). So which one do I use? If the decision fits in a condition, ifelse: it is vectorised and faster. If the function is yours and already written with if (or does several things with each element), sapply saves you rewriting it.
And the anonymous function from before, function(o) round(pnorm(o, …), 3), is the same as classify, but without a name: you write it inside the call because you are only going to use it there. The o is its argument, and sapply gives it the value of each target: 24, then 25, then 26 and then 27.
The normal inside your functions
The normal functions (dnorm, pnorm, qnorm, rnorm) are used inside yours like any other:
# A function with the normal inside: probability of beating a time
prob_under <- function(target, avg, sdev) {
stopifnot(sdev > 0)
pnorm(target, mean = avg, sd = sdev)
}
round(prob_under(25, avg = 26, sdev = 1.5), 4)
qnorm(0.9, mean = 26, sd = 1.5) # the time I only go over 10 % of the time
Output:
[1] 0.2525 [1] 27.92233
The probability of going under 25 minutes is 0.2525 (one race in four). And qnorm(0.9, …) says that 90 % of my races are under 27.92 minutes: if one day it takes me 28, it was one of the bad ones.
Why such a short function? Because it names what it does (prob_under reads better than pnorm), it checks the standard deviation (a negative one would give NaN with a warning) and, since pnorm is vectorised, so is it: prob_under(c(24, 25), 26, 1.5) works without changing anything.
Passing the variance where R asks for the standard deviation. R’s normal functions use sd, the standard deviation. If the problem says N(26, 2.25) and 2.25 is the variance, the argument is sd = 1.5. You will see it with its number in the common mistakes.
pnorm and qnorm, read out loud
The two functions are the same question asked in opposite directions:
pnorm(target, …)is “with what probability do I go under this time?”. A time goes in and a probability comes out: the area of the bell to the left of the time.qnorm(p, …)is “what time do I stay under with probability p?”. A probability goes in and a time comes out. It ispnormbackwards.
Where the two numbers from prob_under and qnorm come from, with the standardisation from topic 5:
| Step | Calculation | Why |
|---|---|---|
| 1 | z = (25 − 26) / 1.5 = −2/3 ≈ −0.67 | standardise: how many standard deviations 25 is below the mean |
| 2 | P(Z < −2/3) = 0.2525 | it is pnorm(-2/3); with the table and −0.67 already rounded you would get 0.2514, which is why it is better to let R use the exact value |
| 3 | z for 90 % = 1.28 | the value of the standard normal that leaves 90 % below it: qnorm(0.9) |
| 4 | 26 + 1.28 · 1.5 = 27.92 | undo the standardisation: the mean plus z standard deviations |
And the proof that one undoes the other:
# pnorm and qnorm undo each other qnorm(0.9, mean = 26, sd = 1.5) # probability -> time pnorm(27.92233, mean = 26, sd = 1.5) # time -> probability pnorm(-2/3) # 25 minutes, already standardised
Output:
[1] 27.92233 [1] 0.9000003 [1] 0.2524925
The second line gives 0.9000003 and not 0.9 because I passed it 27.92233, which is already rounded: the 90 % time gives back the 90 %. And the third is the same 0.2525 as prob_under(25, …): standardising and calling pnorm without mean or sd is the same as giving it the mean and the standard deviation.
If you are torn between the two, look at what you have in your hand. A time, and they ask you for a probability? pnorm. A probability (“the worst 10 % of my races”) and they ask you for a time? qnorm. And remember that pnorm always gives the area on the left: for “taking more than 28 minutes” it is 1 - pnorm(28, 26, 1.5), 0.09.
Simulating a transformation
If T, the 5 km time, is normal, what is the average speed V = 5 / (T/60) in km/h like? Topic 6 teaches you to get its density by hand with a change of variable; simulating, it is enough to transform the simulated values:
# Simulating a transformation: the average speed in km/h if T5 ~ N(26, 1.5) set.seed(21) times <- rnorm(10000, mean = 26, sd = 1.5) speed <- 5 / (times / 60) # km/h, for all 10,000 at once round(c(mean = mean(speed), naive_theory = 5 / (26 / 60)), 3) round(quantile(speed, c(0.05, 0.5, 0.95)), 2)
Output:
mean naive_theory
11.573 11.538
5% 50% 95%
10.52 11.54 12.73
Ten thousand times, ten thousand speeds, not a single loop. And a surprise: the simulated mean speed is 11.573 km/h, but the speed at the mean (5 km in 26 minutes) is 11.538. The mean of a transformation is not the transformation of the mean, unless the transformation is linear; here it is not (it is a division). The difference is small, but it is there, and the simulation catches it without a single integral.
hist(speed, breaks = 40, freq = FALSE, main = "Average speed over 5 km",
xlab = "km/h", ylab = "Density", col = "#A99EF5", border = "white")
In the drawing, the histogram of the speeds looks like a bell, but not quite: the right tail (the very fast races) stretches a little further than the left one. The 5th percentile is 1.02 km/h below the median (10.52 against 11.54) and the 95th, 1.19 above (12.73). With freq = FALSE, the vertical axis is the density (the areas add up to 1), which is how a histogram is compared with a theoretical curve.
Why the average speed comes out higher
The sentence “the mean of a transformation is not the transformation of the mean” can be seen with just two races. First, where the 300 in the code comes from: 5 / (t / 60) = 5 · 60 / t = 300 / t. Going from minutes to km/h is dividing 300 by the time.
Now, a fast race and a slow one, both 2 minutes away from the mean: 24 and 28.
# Two races, a fast one and a slow one, at the same distance from 26 speed2 <- 300 / c(24, 28) # 5 / (t / 60) is the same as 300 / t round(speed2, 2) round(mean(speed2), 2) # the mean of the speeds round(300 / 26, 2) # the speed of the mean
Output:
[1] 12.50 10.71 [1] 11.61 [1] 11.54
| Time | Speed | Against 11.54 | Why |
|---|---|---|---|
| 24 min | 12.50 km/h | +0.96 | going 2 minutes faster raises the speed a lot: you divide 300 by a smaller number |
| 28 min | 10.71 km/h | −0.82 | going 2 minutes slower lowers it, but less |
| mean | 11.61 km/h | +0.07 | what the fast one gains the slow one does not lose, so the mean ends up above 11.54 |
The times are at the same distance from 26, one on each side, and the speeds are not. The curve of 300 / t bends: near the short times it climbs fast and at the long ones it drops slowly. With the 10,000 simulated races the same thing happens on a big scale (11.573 against 11.538), and that is why the right tail of the histogram is the longer one.
If the transformation were linear, like going from minutes to seconds (60 · T), there would be no difference at all: the mean of 60 · T is 60 · 26 = 1560 seconds, exactly.
Check you’ve got it: the median of the simulated speed is 11.54, the same as 300 / 26. Why does it match for the median?
Because the median only depends on the order, and 300 / t keeps the order (turning it around, but keeping it): the shortest time gives the highest speed, the second shortest the second highest, and so on for all of them. The race right in the middle of the times is the one right in the middle of the speeds. With seed 21, the median of the times is 25.995, and 300 / 25.995 = 11.54.
The same happens with the quantiles, but switching sides: the 5 % of the speeds (10.52) comes from the 95 % of the times (28.52 minutes), because the slowest races are the ones with the lowest speed. The mean is not so lucky: it adds values up, and the sum does notice that the curve bends.
The complete program: a season of 5 and 10 km races
Now the big simulation: many 5 and 10 km races. The model is T5 ~ N(26, 1.5) and T10 = 2 · T5 + 1 + E, where E ~ N(0, 1.5) is what the 10 km has of its own (the wind, the hill, how I slept). We want the covariance and the correlation, the probability of going under 50 minutes in the 10 km and to classify each race as “sub-50” or “normal”.
Version 1: with a loop and an if per race
This is how almost everyone would write it coming from Python or Java:
# Version 1: simulate the 10 km season with a loop and an if per race
simulate_v1 <- function(n) {
t5 <- numeric(n); t10 <- numeric(n); level <- character(n)
for (i in 1:n) {
t5[i] <- rnorm(1, mean = 26, sd = 1.5)
t10[i] <- 2 * t5[i] + 1 + rnorm(1, mean = 0, sd = 1.5)
if (t10[i] < 50) {
level[i] <- "sub-50"
} else {
level[i] <- "normal"
}
}
data.frame(t5, t10, level)
}
set.seed(3)
head(simulate_v1(5), 3)
Output:
t5 t10 level 1 24.55710 49.67541 sub-50 2 26.38818 52.04817 normal 3 26.29367 53.63253 normal
It is well written: it reserves the three vectors before the loop (numeric(n) and character(n)), each lap simulates one race and the if classifies it. The first race: 24.56 minutes in the 5 km and 49.68 in the 10, so “sub-50”. Let us check the structure: 2 · 24.5571 + 1 = 50.1142, and the noise of that race has brought it down to 49.68.
Version 2: vectorised
The same idea, but asking rnorm for all n values at once and classifying with ifelse:
# Version 2: the same, vectorised (no loop)
simulate_v2 <- function(n, avg = 26, sdev = 1.5, noise = 1.5) {
stopifnot(n >= 1, sdev > 0, noise >= 0)
t5 <- rnorm(n, mean = avg, sd = sdev)
t10 <- 2 * t5 + 1 + rnorm(n, mean = 0, sd = noise)
level <- ifelse(t10 < 50, "sub-50", "normal")
data.frame(t5, t10, level)
}
set.seed(3)
head(simulate_v2(5), 3)
Output:
t5 t10 level 1 24.55710 50.15939 normal 2 25.56121 52.25055 normal 3 26.38818 55.45128 normal
Four lines of body instead of ten, and arguments to change the model without touching the code. But notice: with the same seed, the first race has the same 5 km (24.5571) and a different 10 km. A bug? No. Version 1 asks for the random numbers in the order 5 km, 10 km, 5 km, 10 km…; version 2 asks first for all the 5 km ones and then all the noises. The random numbers come from the same sequence, but they are handed out in a different order.
Two correct simulations of the same model do not have to give the same numbers even if they use the same seed. What has to match is the distribution: the means, probabilities and correlations they estimate.
Which random number goes where
The explanation above can be seen number by number. rnorm(1, mean = 26, sd = 1.5) does not make up a time out of nothing: it takes the next number in the seed’s sequence, which is from an N(0, 1), and scales it, 26 + 1.5 · z. The noise the same, but without the 26: 1.5 · z. These are the first 10 z values of seed 3, the ones simulate_v1(5) and simulate_v2(5) use up:
# The first 10 numbers of seed 3, unscaled: N(0, 1) set.seed(3) round(rnorm(10), 4)
Output:
[1] -0.9619 -0.2925 0.2588 -1.1521 0.1958 0.0301 0.0854 1.1166 -1.2189 [10] 1.2674
| No. | z | In version 1 | In version 2 |
|---|---|---|---|
| 1 | −0.9619 | 5 km of race 1 | 5 km of race 1 |
| 2 | −0.2925 | noise of race 1 | 5 km of race 2 |
| 3 | 0.2588 | 5 km of race 2 | 5 km of race 3 |
| 4 | −1.1521 | noise of race 2 | 5 km of race 4 |
| 5 | 0.1958 | 5 km of race 3 | 5 km of race 5 |
| 6 | 0.0301 | noise of race 3 | noise of race 1 |
| 7 | 0.0854 | 5 km of race 4 | noise of race 2 |
| 8 | 1.1166 | noise of race 4 | noise of race 3 |
| 9 | −1.2189 | 5 km of race 5 | noise of race 4 |
| 10 | 1.2674 | noise of race 5 | noise of race 5 |
The two versions go together at number 1, split at number 2 and match again at number 10. Now the outputs fit on their own. The z number 3 (0.2588) gives 26 + 1.5 · 0.2588 = 26.39 minutes: in version 1 it is the 5 km of race 2 (26.38818) and in version 2 that of race 3 (26.38818, the same one). Both versions use up the same numbers; what changes is which cell each one goes to.
Check you’ve got it: race 1 has the same 5 km in both versions, but the 10 km is 49.68 in one and 50.16 in the other. Which z does each one use for the noise?
Version 1 uses z number 2 (−0.2925), because it asks for the noise right after the 5 km of the same race. Its 10 km is 2 · 24.5571 + 1 + 1.5 · (−0.2925) = 50.1142 − 0.4388 = 49.68: “sub-50”.
Version 2 does not ask for any noise until it has the five 5 km times, so the one for race 1 is z number 6 (0.0301): 50.1142 + 1.5 · 0.0301 = 50.1142 + 0.0452 = 50.16, “normal”. Same race, same model, different luck. That is why the note says that what has to match is the distribution, not each number.
How much faster? system.time
system.time(expression) runs the expression and tells you how long it took:
# How much faster? We measure with system.time set.seed(1); system.time(d1 <- simulate_v1(200000)) set.seed(1); system.time(d2 <- simulate_v2(200000))
Output:
user system elapsed 0.000 0.000 2.427 user system elapsed 0.000 0.000 0.061
The column that matters is elapsed (real time, in seconds): 2.427 with the loop and 0.061 vectorised, about 40 times faster. (In the site’s playground user and system show 0 because the browser does not measure them; in RStudio you will see numbers there too. And the times change from one computer to another and from one run to the next: what stays is the ratio.)
Where does the difference come from? In version 1, R interprets the lines of the loop 200,000 times: it calls rnorm 400,000 times asking for one number each time and evaluates 200,000 ifs. In version 2, it calls rnorm twice asking for 200,000 numbers, and the real work happens in compiled code.
The joint distribution: covariance, correlation and a probability
With the fast version we can simulate 100,000 races and compare with what topic 6 says:
# The joint distribution: covariance, correlation and a probability, simulated against theoretical set.seed(99) d <- simulate_v2(100000) round(c(cov = cov(d$t5, d$t10), cor = cor(d$t5, d$t10)), 3) round(c(cov_theory = 2 * 1.5^2, cor_theory = 2 * 1.5^2 / (1.5 * sqrt(4 * 1.5^2 + 1.5^2))), 3) round(c(simulated = mean(d$t10 < 50), theoretical = pnorm(50, mean = 53, sd = sqrt(11.25))), 4) table(d$level)
Output:
cov cor
4.482 0.894
cov_theory cor_theory
4.500 0.894
simulated theoretical
0.1881 0.1855
normal sub-50
81191 18809
Where each theoretical number comes from (the properties are the ones in topic 6):
- Covariance: Cov(T5, 2·T5 + 1 + E) = 2 · Var(T5) = 2 · 1.5² = 4.5. The simulated one, 4.482.
- Correlation: 4.5 / (1.5 · SD(T10)), with Var(T10) = 4 · 2.25 + 2.25 = 11.25. It comes out as 0.894, the same as the simulated one.
- T10 is normal, with mean 2 · 26 + 1 = 53 and standard deviation √11.25 = 3.354, so P(T10 < 50) =
pnorm(50, 53, sqrt(11.25))= 0.1855. The simulated one, 0.1881. - And the table counts the races: 18,809 “sub-50” out of 100,000, which is that same proportion.
The chart that shows the relationship between the two variables is the scatter plot:
plot(d$t5[1:300], d$t10[1:300], pch = 19, col = "#5B4BDB80",
main = "My 5 km against my 10 km (300 simulated races)",
xlab = "5 km time (min)", ylab = "10 km time (min)")
abline(a = 1, b = 2, col = "#FF6B4A", lwd = 2)
In the drawing, the cloud goes up from left to right and is narrow: if the 5 km was fast, the 10 km usually is too. That is a correlation of 0.89. The coral line is the model’s, T10 = 1 + 2 · T5 (abline(a = 1, b = 2): intercept 1 and slope 2); the points move away from it by what the noise E measures. I only draw 300 of the 100,000 ([1:300]): with all of them, the cloud would be a smudge. And the colour "#5B4BDB80" has two more digits at the end, 80, which make it semi-transparent, so you can see where the points pile up.
The topic 6 sums, property by property
The list further up chains several properties in a few lines. Here they are one per row, each with the rule that justifies it. The key to almost all of them is that the noise E has nothing to do with the 5 km (it is independent of T5), and that is why many things cancel out:
| What | Calculation | Why |
|---|---|---|
| Mean of T10 | 2 · 26 + 1 + 0 = 53 | the expectation is linear and the noise has mean 0 |
| Variance of T10 | 2² · 1.5² + 1.5² = 9 + 2.25 = 11.25 | the 2 comes out squared; the +1 does not change the spread; and since the noise is independent of T5, the variances add up with no covariance term |
| Standard deviation of T10 | √11.25 = 3.354 | the standard deviation is the square root of the variance |
| Covariance | Cov(T5, T10) = 2 · Var(T5) + Cov(T5, E) = 2 · 2.25 + 0 = 4.5 | the covariance splits over each sum; the constant 1 adds nothing; and two independent variables have covariance 0 |
| Correlation | 4.5 / (1.5 · 3.354) = 0.894 | the covariance divided by the product of the two standard deviations |
| P(T10 < 50) | z = (50 − 53) / 3.354 = −0.894, and P(Z < −0.894) = 0.1855 | T10 is normal (a normal times 2, plus a constant, plus another independent normal) and is standardised as always |
Did you see that 0.894 comes up twice? It is a coincidence of this model, not a rule. The correlation is 2 · 1.5 / 3.354 = 3 / 3.354, and the z is −3 / 3.354 because 50 is exactly 3 minutes below 53. If the target were going under 52 minutes, the z would be (52 − 53) / 3.354 = −0.30 and the correlation would still be 0.894.
Adding the standard deviations instead of the variances. The standard deviation of T10 is not 2 · 1.5 + 1.5 = 4.5, but √(9 + 2.25) = 3.354. With 4.5 the correlation would come out as 4.5 / (1.5 · 4.5) = 0.67 and the probability, pnorm(50, 53, 4.5) = 0.25. The simulation (0.894 and 0.1881) would tell you straight away that something does not add up.
Check you’ve got it: in “Try it in the R playground”, d3 uses noise = 4. What correlation should you see?
About 0.6. Only the variance of the noise changes: Var(T10) = 4 · 2.25 + 4² = 9 + 16 = 25, so the standard deviation of T10 becomes 5. The covariance does not change, it is still 2 · 2.25 = 4.5, because the noise has nothing to do with the 5 km. The correlation is 4.5 / (1.5 · 5) = 0.6.
With the script in that section you get 0.604: close, but not exact, because it is 20,000 races and not infinitely many. More noise of the 10 km’s own widens the cloud and weakens the relationship, even though the model’s line, T10 = 1 + 2 · T5, is the same.
Common mistakes (with R’s real message)
Using if with a vector.
if (t5 < 26) "good"
Output:
Error in if (t5 < 26) "good" : the condition has length > 1
“the condition has length > 1”: if needs one TRUE or FALSE, and t5 < 26 is 8 of them. Since R 4.2 it is an error (before, it was a warning and only looked at the first one, which was even worse). If you want to decide for each element, ifelse; if you want to know whether it holds for any or for all, any() or all().
Recycling that does not fit.
c(27.4, 26.1, 25.8) - c(1, 2)
Output:
[1] 26.4 24.1 24.8 Warning message: In c(27.4, 26.1, 25.8) - c(1, 2) : longer object length is not a multiple of shorter object length
It calculates, but warns: “longer object length is not a multiple of shorter object length”. It has subtracted 1, 2 and then 1 again. This almost always means that one of the two vectors is not the one you thought (you are missing a value or have one too many). Read the warnings: R does not print them for decoration.
apply on a data frame with text.
races <- data.frame(race = c("New Year's Eve run", "Beach"), t5 = c(25.2, 26.3))
apply(races, 1, function(row) row["t5"] / 5)
Output:
Error in row["t5"]/5 : non-numeric argument to binary operator
“non-numeric argument to binary operator”: apply turns the data frame into a matrix, and a matrix has only one type; since there is a text column, everything becomes text, and "25.2" / 5 cannot be divided. With data frames, work with the columns directly (races$t5 / 5, which is also vectorised) or with sapply on the column.
cor with a single vector.
cor(d$t5)
Output:
Error in cor(d$t5) : supply both 'x' and 'y' or a matrix-like 'x'
“supply both ‘x’ and ‘y’ or a matrix-like ‘x'”: correlation is between two variables. Either give it both (cor(d$t5, d$t10)) or a matrix or data frame with several numeric columns (cor(d[, c("t5", "t10")]), which gives the correlation matrix).
The variance instead of the standard deviation.
pnorm(25, mean = 26, sd = 2.25) # 2.25 is the variance, not the standard deviation! pnorm(25, mean = 26, sd = 1.5)
Output:
[1] 0.3283606 [1] 0.2524925
No message: R cannot know you got it wrong. With the variance it comes out as 0.328; with the standard deviation, the right one, 0.252. If the normal is written as N(μ, σ²), take the square root before calling pnorm.
Vectorising “halfway”: calling rnorm(1, …) inside an sapply over 100,000 elements. It is as slow as the loop, because it still asks for the numbers one at a time. Vectorising means asking for all n at once.
Try it in the R playground
Copy the script into the R playground on the site and run it. It has everything inside.
simulate <- function(n, avg = 26, sdev = 1.5, noise = 1.5) {
stopifnot(n >= 1, sdev > 0, noise >= 0)
t5 <- rnorm(n, mean = avg, sd = sdev)
t10 <- 2 * t5 + 1 + rnorm(n, mean = 0, sd = noise)
data.frame(t5, t10, level = ifelse(t10 < 50, "sub-50", "normal"))
}
set.seed(99)
d <- simulate(20000)
cor(d$t5, d$t10)
mean(d$t10 < 50)
plot(d$t5[1:300], d$t10[1:300], pch = 19, col = "#5B4BDB80",
xlab = "5 km (min)", ylab = "10 km (min)")
abline(a = 1, b = 2, col = "#FF6B4A", lwd = 2)
d3 <- simulate(20000, noise = 4) # a much more unpredictable 10 km
cor(d3$t5, d3$t10)
What to look at:
- Compare the two correlations: with
noise = 4, how much does it drop? Plotd3and watch the cloud widen. - In Environment,
dis a data frame with 20,000 rows and 3 columns; typeView(d)(or click on it) to see it as a table. - Measure the difference yourself:
system.time(simulate(200000)). How long does it take in your browser? - Type
simulate(10, sdev = -1)and read thestopifnotmessage.
Summary
| Piece | What for | Example from the article |
|---|---|---|
| Operations on vectors | the whole vector at once | t5 / 5, sum(t5 < 26) |
ifelse(cond, a, b) | one if per element | “good” / “normal” |
| Recycling | the short vector repeats | t5 - mean(t5) |
apply(M, 1 or 2, f) | by rows or by columns | mean per week |
sapply(v, function(x) …) | any function, element by element | probability per target |
rnorm, pnorm, qnorm in functions | the normal inside your code | prob_under(25, 26, 1.5) = 0.2525 |
cov, cor, plot(x, y) | joint variables | correlation 0.894 |
system.time(expr) | measure how long it takes | loop 2.4 s, vectorised 0.06 s |
Three ideas to take with you:
- Think in vectors, not in cells. If you write
x[i]inside a loop, ask yourself whether the same operation on the wholexwould do the same thing. - Ask for the random numbers all at once.
rnorm(n, …)and notntimesrnorm(1, …): that is most of the speed. - Simulating transforms without integrating. To know the distribution of g(X), simulate X and apply g to all the values: the histogram, the mean and the quantiles come out by themselves.
What next?
In the R intensive 3 exercises you will vectorise loops, write functions with the normal inside, simulate joint variables and time your own versions with system.time, with the cheat sheet for the block.
Next, block 4: limit theorems and sampling, with the Monte Carlo method: simulating the central limit theorem, the law of large numbers and Chebyshev’s inequality.
Did this article help you? Here is how you can support SergioLearns →
Next step: exercisesR intensive 3: normal and joint distributions — exercises with the faculty coffee machine, ifelse, sapply and a million cups (and the && that no longer forgives)Next block: 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


