R intensive 3: normal and joint distributions — exercises with the faculty coffee machine, ifelse, sapply and a million cups (and the && that no longer forgives)

To classify the cups from the coffee machine I wrote ifelse(ml > 140 && ml < 165, "ok", "bad") and R answered with an error I had never seen: since R 4.3, && with a vector no longer warns, it stops. Before, it quietly took the first element and gave a wrong answer; now it forces you to choose between & (vector) and && (a single value).

This article is the hands-on part of block 3 of the R intensive. The theory (operations on vectors, ifelse, apply and sapply, matrices, rnorm/pnorm/qnorm inside functions and system.time) is in R intensive 3: normal and joint distributions. The statistics are taken as known: the normal, in the normal distribution exercises, and covariance and transformations, in the ME1 transformations and joint distributions exercises. What you train here is a way of thinking: working with the whole vector at once instead of element by element.

How to use this article

  1. Open the R playground (or RStudio). Each exercise sets its seed: with the same order of commands, you will get the same numbers.
  2. Level 1, reproduce and read; level 2, write a function that uses qnorm and pnorm and apply it to several cases with sapply; 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 10-question test and copy “For your script” into your .R.

The machine in the exercise. It serves white coffees in 165 ml cups: if it pours more, it spills; if it pours less than 140 ml, the cup is short. The amount served is modelled as a normal. Made-up data, a scene from any faculty corridor.

Level 1: reproduce and read the outputs

set.seed(27)
ml <- round(rnorm(12, mean = 150, sd = 8), 1)
ml
status <- ifelse(ml < 140, "short", ifelse(ml > 165, "spill", "ok"))
status
table(status)
round(pnorm(140, mean = 150, sd = 8), 4)
round(1 - pnorm(165, mean = 150, sd = 8), 4)
round(qnorm(0.95, mean = 150, sd = 8), 2)
  1. How many of the 12 cups spill and how many are short?
  2. Why are there two ifelse, one inside the other?
  3. What proportion of cups does the model expect to be short, and what proportion to spill? Does it match the 12 cups?
  4. What does the 163.16 from qnorm mean?

ifelse(condition, yes, no) evaluates the condition on every element and returns a vector of the same size. For three categories, the “no” of the first is another ifelse.

Level 2: write the function that tunes the machine

The technician wants at most 1 % of cups to spill. If the machine’s standard deviation is σ \sigma , the mean to programme is the one that leaves 1 % above 165 ml: μ=165−z0.99 σ \mu = 165 – z_{0.99}\,\sigma .

Write tune(sd, limit = 165, risk = 0.01, minimum = 140) that returns a named vector: the sd, the mean to programme (2 decimal places) and p_short, the probability that with that mean a cup ends up below minimum (4 decimal places). Then apply it with a single command to standard deviations of 4, 6, 8 and 10 ml and present the result as a table with one row per standard deviation.

Expected result for tune(8):

      sd     mean  p_short 
  8.0000 146.3900   0.2122 

qnorm(0.99) is the standard normal quantile that leaves 1 % to the right (2.33). To apply the function to several standard deviations, sapply(c(4, 6, 8, 10), tune) returns a matrix with one column per standard deviation; t() turns it round.

Level 3 (challenge): ten thousand cortados, in the exam format

Exercise (15 points). The machine first pours the coffee, X∼N(60,4) X \sim N(60, 4) ml, and then the milk, which a sensor adjusts to the coffee that came out: Y=90+0.5 (X−60)+ε Y = 90 + 0.5\,(X – 60) + \varepsilon , with ε∼N(0,5) \varepsilon \sim N(0, 5) independent of X X . The cup’s total is T=X+Y T = X + Y .

  • a) (3 points) With set.seed(30), simulate 10,000 cups and store them in a two-column matrix cups (coffee, milk). Give its dimension and, with apply, the mean and standard deviation of each column (2 decimal places).
  • b) (4 points) Compute the covariance and correlation matrices (2 decimal places) and draw the scatter plot of the first 500 cups, with a title and axes. What sign does the relationship have, and why?
  • c) (4 points) Compute total without loops, its simulated mean and variance, and compare them with the theoretical ones: E[T]=150 E[T] = 150 and Var(T)=Var(X)+Var(Y) \mathrm{Var}(T) = \mathrm{Var}(X) + \mathrm{Var}(Y) +2 Cov(X,Y)=61 {} + 2\,\mathrm{Cov}(X, Y) = 61 . Estimate P(T>165) P(T > 165) by simulation and with pnorm.
  • d) (4 points) For a million cups of N(150,8) N(150, 8) , label each one "spill" or "ok" in two ways: with a for loop and an if, and with ifelse. Time both with system.time and check that they give the same.

The columns of a matrix are taken by name, cups[, "coffee"], and added like vectors. In apply(m, 2, f), the 2 means “by columns” (1 would be by rows).

Solutions

Level 1

Before opening the solution, the plan. The four questions aren’t answered the same way: some look at the 12 cups that came out and others look at the model, the normal with mean 150 and standard deviation 8. Telling them apart is half the exercise.

QuestionLook at…CommandWhy
How many spill and how many are shortthe 12 cupstable(status)it’s counting what came out; the model plays no part here
Why two ifelsethe codeone ifelse inside anotherthere are three categories and each ifelse can only split in two
What proportion the model expectsthe normalpnorm(140, …) and 1 - pnorm(165, …)pnorm gives the area to the left; spilling means landing to the right of 165
What the 163.16 isthe normalqnorm(0.95, …)it goes the other way: from probability to millilitres

And the obvious move, comparing the 2 out of 12 with the 0.0304 as they are? You can’t: one counts cups and the other is a probability. That’s why the solution turns the probability into cups: 12 · 0.0304 = 0.36.

See the level 1 solution
set.seed(27)
ml <- round(rnorm(12, mean = 150, sd = 8), 1)
ml
status <- ifelse(ml < 140, "short", ifelse(ml > 165, "spill", "ok"))
status
table(status)

Output:

 [1] 165.3 159.2 143.9 138.3 141.3 152.4 150.1 159.3 167.1 151.9 139.7
[12] 150.3
 [1] "spill" "ok"    "ok"    "short" "ok"    "ok"    "ok"    "ok"   
 [9] "spill" "ok"    "short" "ok"   
status
   ok short spill 
    8     2     2 
  1. Two spill (165.3 and 167.1 ml, cups 1 and 9) and two are short (138.3 and 139.7, cups 4 and 11). The other eight are fine.
  2. Because there are three categories. The first ifelse separates the short ones from the rest; for the rest, the “no” is another ifelse that separates those that spill from those that are fine. R evaluates both conditions on all 12 cups at once: there is no loop at all.
round(pnorm(140, mean = 150, sd = 8), 4)
round(1 - pnorm(165, mean = 150, sd = 8), 4)
round(qnorm(0.95, mean = 150, sd = 8), 2)

Output:

[1] 0.1056
[1] 0.0304
[1] 163.16
  1. The model expects 10.56 % of cups to be short and 3.04 % to spill. Out of 12 cups, that would be 1.27 short and 0.36 spilled; 2 and 2 came out. With 12 cups, drifting like that is normal: 3 % of 12 is not even half a cup, and one extra is enough to make the proportion jump. With 10,000 cups (level 3) the numbers get much closer.
  2. It is the 95th percentile: 95 % of the cups carry 163.16 ml or less. Notice that 1 - pnorm(…) and qnorm(…) are inverse operations: one goes from millilitres to probability and the other from probability to millilitres.

Writing pnorm(165, mean = 150, sd = 8) for “it spills”. It gives 0.9696, which is the probability of not spilling: the area to the left of 165. If almost every cup spilled, you would have seen it in your 12.

Check you’ve got it: which command gives the probability that a cup comes out fine, and how many of the 12 would you expect?

pnorm(165, mean = 150, sd = 8) - pnorm(140, mean = 150, sd = 8), which is 0.8640. It’s everything to the left of 165 minus what was already short (or 1 − 0.1056 − 0.0304). Out of 12 cups, 12 · 0.8640 = 10.37 fine; 8 came out, because each tail took one cup too many.

Level 2

Before the function, the sum on paper for σ=8 \sigma = 8 . The temptation is to try means with pnorm until you get 1 % (148? 146?). It works, but it’s guessing. The direct route is to write down the condition and solve for the mean:

StepWorkingWhy
1. What’s askedP(X>165)=0.01 P(X > 165) = 0.01 at most 1 % of cups above the rim
2. StandardiseP(Z>165−μ8)=0.01 P\left(Z > \frac{165 – \mu}{8}\right) = 0.01 subtracting the mean and dividing by σ \sigma turns any normal into the standard one
3. Quantile165−μ8=z0.99=2.326 \frac{165 – \mu}{8} = z_{0.99} = 2.326 the value that leaves 1 % to the right leaves 99 % to the left: qnorm(0.99)
4. Solveμ=165−2.326⋅8=146.39 \mu = 165 – 2.326 \cdot 8 = 146.39 it’s the formula in the statement, with numbers
5. The short onesP(X<140)=P(Z<−0.80)=0.2122 P(X < 140) = P(Z < -0.80) = 0.2122 (140−146.39)/8=−0.80 (140 – 146.39)/8 = -0.80 , and pnorm gives the area to the left

The function just copies steps 3, 4 and 5, replacing 8 with sd, 165 with limit, 0.01 with risk and 140 with minimum.

See the level 2 solution
# tune(): the mean that leaves a 'risk' of cups above 'limit', and the short cups that result
tune <- function(sd, limit = 165, risk = 0.01, minimum = 140) {
  stopifnot(sd > 0, risk > 0, risk < 1)
  mu <- limit - qnorm(1 - risk) * sd              # mu = limit - z_(1 - risk) * sigma
  c(sd = sd, mean = round(mu, 2), p_short = round(pnorm(minimum, mu, sd), 4))
}
tune(8)
t(sapply(c(4, 6, 8, 10), tune))

Output:

      sd     mean  p_short 
  8.0000 146.3900   0.2122 
     sd   mean p_short
[1,]  4 155.69  0.0000
[2,]  6 151.04  0.0329
[3,]  8 146.39  0.2122
[4,] 10 141.74  0.4311
Tuning the machine by its standard deviationTwo line charts against the standard deviation 4, 6, 8 and 10. Left: the mean needed falls from 155.69 to 141.74 ml. Right: the probability of a short cup rises from 0 to 0.4311.140145150155160Programmed mean (ml)Mean needed155.694151.046146.398141.7410Machine standard deviation (ml)00.10.20.30.40.5P(short cup)Short cups0.000040.032960.212280.431110Machine standard deviation (ml)
The more irregular the machine, the lower the mean has to be and the more cups end up short.

How to read it: with a machine of σ=8 \sigma = 8 ml, for only 1 % to spill you have to programme 146.39 ml, and then 21.22 % of the cups end up short: you fix one problem and create another. The table shows where the real solution is: with σ=4 \sigma = 4 a mean of 155.69 ml is enough and practically no cup is short. In the plot, the line of the mean needed goes down and the line of short cups goes up with the standard deviation: what needs improving is how consistent the machine is, not the mean.

Why it is written this way:

  • qnorm(1 - risk) and not qnorm(risk). The 1 % that spills is on the right; qnorm(0.01) gives −2.33 -2.33 and the mean would come out above 165.
  • Arguments with defaults. tune(8) uses 165, 1 % and 140; if the cups change tomorrow, tune(8, limit = 200) without touching the function.
  • sapply instead of a loop. It calls tune with each standard deviation and, as each call returns three numbers, binds the results into a 3 × 4 matrix; t() turns it round so there is one row per machine, which reads better.
  • Round when returning. The unrounded mean is what goes into pnorm; if you round it first, p_short changes in the fourth decimal place.

Why the table says improve the machine, not the mean. Merge steps 4 and 5 of the paper working into a single formula:

P(short)=Φ(140−(165−z0.99 σ)σ)=Φ(z0.99−25σ) P(\text{short}) = \Phi\left(\frac{140 – (165 – z_{0.99}\,\sigma)}{\sigma}\right) = \Phi\left(z_{0.99} – \frac{25}{\sigma}\right)

The mean has vanished: once you fix the 1 % of spills, σ \sigma dictates it. The 25 ml are the gap between 140 and 165. With σ=4 \sigma = 4 , 2.33−6.25=−3.92 2.33 – 6.25 = -3.92 and the area to the left is practically zero; with σ=10 \sigma = 10 , 2.33−2.5=−0.17 2.33 – 2.5 = -0.17 and almost half the cups (0.4311) end up short.

Check you’ve got it: what standard deviation would you need for 1 % to spill and also only 1 % to be short?

About 5.37 ml. If both tails are equal, the mean has to sit right in the middle of the gap, 152.5 ml, and the 12.5 ml to each edge have to be z0.99 z_{0.99} standard deviations: σ=12.5/2.326=5.37 \sigma = 12.5 / 2.326 = 5.37 . In R, 25 / (2 * qnorm(0.99)) gives 5.37, and tune(25 / (2 * qnorm(0.99))) returns mean 152.5 and p_short 0.01.

Level 3

Before simulating, the theory: part c asks you to compare with it and part b, to explain a sign. Careful: here, as in R, N(60,4) N(60, 4) gives the standard deviation, so Var(X)=16 \mathrm{Var}(X) = 16 .

WhatWorkingWhy
E[T] E[T] 60+90=150 60 + 90 = 150 the expectation of a sum is the sum, dependent or not
Var(Y) \mathrm{Var}(Y) 0.52⋅16+25=29 0.5^2 \cdot 16 + 25 = 29 the 90 doesn’t vary; multiplying by 0.5 multiplies the variance by 0.52 0.5^2 ; the noise is independent and adds its own
Cov(X,Y) \mathrm{Cov}(X, Y) 0.5⋅16=8 0.5 \cdot 16 = 8 the only part of Y Y that covaries with X X is 0.5 X 0.5\,X ; the noise contributes 0
Var(T) \mathrm{Var}(T) 16+29+2⋅8=61 16 + 29 + 2 \cdot 8 = 61 variance of a sum of variables that are not independent

With these numbers you already know what has to come out; if the simulation strays far, the bug is in the code.

And why build the milk from coffee, instead of simulating it directly with mean 90 and standard deviation 29 \sqrt{29} ? Because each cup would lose the sensor’s adjustment:

# The obvious move: simulate the milk with its mean and standard deviation, ignoring the coffee
set.seed(30)
coffee <- rnorm(10000, mean = 60, sd = 4)
milk_wrong <- rnorm(10000, mean = 90, sd = sqrt(29))   # same mean and same sd as the right milk
round(c(sd_milk = sd(milk_wrong), cov = cov(coffee, milk_wrong), var_total = var(coffee + milk_wrong)), 2)

Output:

  sd_milk       cov var_total 
     5.39      0.53     45.96 

The milk has the right standard deviation (5.39), but its covariance with the coffee stays at 0.53, noise around 0, and the variance of the total drops to 45.96: that’s the 45 you get by forgetting the covariance. Each column is fine; what fails is the relationship between them, exactly what part b asks about.

See the level 3 solution

a) The matrix of cups (3 points).

# ==== Exercise 3a: simulate 10,000 cups ====
set.seed(30)
coffee <- rnorm(10000, mean = 60, sd = 4)
milk   <- 90 + 0.5 * (coffee - 60) + rnorm(10000, mean = 0, sd = 5)   # no loop: 10,000 at once
cups   <- cbind(coffee, milk)                                        # 10000 x 2 matrix with names
dim(cups)
round(apply(cups, 2, mean), 2)
round(apply(cups, 2, sd), 2)

Output:

[1] 10000     2
coffee   milk 
 60.05  90.05 
coffee   milk 
  3.98   5.43 

The milk is computed in one go for the 10,000 cups: coffee - 60 is a vector, 0.5 * … too, and rnorm(10000, …) adds a different noise to each one. Means of 60.05 and 90.05 ml (the theory, 60 and 90); standard deviations of 3.98 and 5.43 ml. The milk’s is larger than the noise’s 5 because it also inherits variation from the coffee: 0.52⋅16+25=29=5.39 \sqrt{0.5^2 \cdot 16 + 25} = \sqrt{29} = 5.39 .

b) Covariance, correlation and scatter plot (4 points).

# ==== Exercise 3b: relationship between coffee and milk ====
round(cov(cups), 2)
round(cor(cups), 2)
plot(cups[1:500, "coffee"], cups[1:500, "milk"],
     main = "Coffee and milk in 500 cups", xlab = "Coffee (ml)", ylab = "Milk (ml)", pch = 20)

Output:

       coffee  milk
coffee  15.88  8.44
milk     8.44 29.48
       coffee milk
coffee   1.00 0.39
milk     0.39 1.00
Scatter plot of coffee and milk in 500 cupsOutput of plot: 500 points with coffee on the horizontal axis, from 45 to 75 ml, and milk on the vertical, from 70 to 105 ml. The cloud rises from left to right and is wide; a dashed line marks 90 + 0.5 (coffee − 60).708090100110Milk (ml)45505560657075– – 90 + 0.5 (coffee − 60)Coffee (ml)cor = 0.39
Redrawn in the site colours: the cloud rises (positive covariance) but strays far from the line (moderate correlation).

The covariance is positive (8.44; the theoretical one is 0.5⋅16=8 0.5 \cdot 16 = 8 ) and the correlation, 0.39: a positive, moderate linear relationship. It is positive because the sensor pours more milk when more coffee has come out; it is moderate because the 5 ml of noise weighs more than the adjustment. In the plot, the cloud rises from left to right, but it is wide: with 60 ml of coffee you can find cups with 80 or with 100 ml of milk. Only 500 cups go into the plot so something can be seen; with 10,000, the cloud would be a blob.

cov and cor applied to a matrix give the whole matrix at once. The diagonal of cov holds the variances (15.88 and 29.48); off the diagonal, the covariance, repeated because Cov(X,Y)=Cov(Y,X) \mathrm{Cov}(X, Y) = \mathrm{Cov}(Y, X) .

c) The cup’s total (4 points).

# ==== Exercise 3c: T = X + Y without loops ====
total <- cups[, "coffee"] + cups[, "milk"]
round(c(mean = mean(total), var = var(total)), 2)
round(mean(total > 165), 4)                 # simulated
round(1 - pnorm(165, 150, sqrt(61)), 4)     # theoretical: T is normal (sum of normals)

Output:

  mean    var 
150.10  62.23 
[1] 0.0296
[1] 0.0274

Simulated mean 150.10 (theoretical 150) and variance 62.23 (theoretical 61). The theoretical value comes from 16+29+2⋅8=61 16 + 29 + 2 \cdot 8 = 61 : forget the covariance and you would say 45, and the standard deviation would be 6.71 instead of 7.81. P(T>165) P(T > 165) : 0.0296 simulated against 0.0274 theoretical, about 3 cups in 100.

Adding the variances “because they are two ingredients” without checking whether they are independent. Here they are not (the milk depends on the coffee): the covariance enters the variance of the sum, and the simulation confirms it: 62 is much closer to 61 than to 45.

d) A million cups: loop against vector (4 points).

# ==== Exercise 3d: loop against ifelse ====
set.seed(1)
million <- rnorm(1e6, mean = 150, sd = 8)
system.time({
  s1 <- character(1e6)                     # allocate the vector first
  for (i in seq_along(million)) {
    s1[i] <- if (million[i] > 165) "spill" else "ok"
  }
})
system.time(s2 <- ifelse(million > 165, "spill", "ok"))
identical(s1, s2)

Output:

   user  system elapsed 
  0.000   0.000   2.761 
   user  system elapsed 
  0.000   0.000   0.201 
[1] TRUE

The times are from a single run on the computer where the article was prepared (on yours they will be different), but the ratio repeats on any machine: the loop takes more than ten times longer (compare the two elapsed values: seconds against tenths of a second) and the result is identical. Look at the elapsed column, the wall-clock time: it is what you notice while waiting. The loop makes a million calls to if from R; ifelse does the comparison of a million elements in one go, in compiled code.

How it is marked (indicative, my own, not official). a: 2 points for the simulation without loops with the milk built correctly and 1 for apply. b: 2 for both matrices, 1 for the plot and 1 for interpreting the sign. c: 2 for the total and the comparison (with the covariance) and 2 for the two probabilities. d: 2 for both versions, 1 for timing and 1 for checking they match.

Writing 1 - pnorm(165, 150, 61). pnorm wants the standard deviation, not the variance: with 61 you get 0.40, nothing like the simulated 0.0296. It’s sqrt(61).

Check you’ve got it: if the sensor didn’t adjust the milk (always 90 ml plus the noise), what would Var(T) and the probability of the cup spilling be?

Without the sensor, Y=90+ε Y = 90 + \varepsilon : Var(Y)=25 \mathrm{Var}(Y) = 25 and Cov(X,Y)=0 \mathrm{Cov}(X, Y) = 0 , so Var(T)=16+25=41 \mathrm{Var}(T) = 16 + 25 = 41 and the standard deviation is 41=6.40 \sqrt{41} = 6.40 . Then 1 - pnorm(165, 150, sqrt(41)) gives 0.0096: under 1 %, against 0.0274 with the sensor. The sensor pours more milk precisely when more coffee has already fallen: it pushes the full cups even higher.

What’s wrong here?

Snippet 1. The story from the start, with the cups from level 1.

ifelse(ml > 140 && ml < 165, "ok", "bad")

Output:

Error in ml > 140 && ml < 165 : 'length = 12' in coercion to 'logical(1)'

&& and || are for a single value (the usual ifs): they compare one with one and stop as soon as they know the answer. With a vector of 12, since R 4.3 they give this error; in earlier versions they took only the first element and returned a single "ok" or "bad", without warning.

Using && or || inside ifelse, subset or a filter x[…]. Fix: & and |, which work element by element.

ifelse(ml > 140 & ml < 165, "ok", "bad")

Output:

 [1] "bad" "ok"  "ok"  "bad" "ok"  "ok"  "ok"  "ok"  "bad" "ok"  "bad"
[12] "ok" 

Snippet 2. Warning if any cup spills.

if (ml > 165) print("Check the machine")

Output:

Error in if (ml > 165) print("Check the machine") : the condition has length > 1

if needs one TRUE or FALSE, and ml > 165 is twelve. R does not guess whether you want “any” or “all”, so it stops.

Say which you want: any() (at least one) or all() (every one).

if (any(ml > 165)) print("Check the machine")

Output:

[1] "Check the machine"

Snippet 3. A table with the ml and status of the first three cups, and double the ml of each row.

tab <- data.frame(ml = ml[1:3], status = status[1:3])
apply(tab, 1, function(row) row["ml"] * 2)

Output:

Error in row["ml"] * 2 : non-numeric argument to binary operator

apply works with matrices, and a matrix has a single type. Given a data frame with a text column, R turns it into a text matrix: "165.3" is no longer a number and cannot be multiplied.

Using apply(df, 1, …) with a data frame that mixes numbers and text. Fix: work with the column, which is a vector (and no apply is needed).

tab$ml * 2

Output:

[1] 330.6 318.4 287.8

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(130, 150, 170)
ifelse(x > 160, "high", "ok")
  1. [1] "ok" "ok" "high"
  2. [1] "high"
  3. [1] "ok"
  4. An error: the condition has length 3
Solution

Answer: [1] "ok" "ok" "high"

x > 160 gives FALSE FALSE TRUE and ifelse picks “high” or “ok” at each position.

Question 2Single choice

What happens when you run this in R 4.3 or later?

x <- c(130, 150, 170)
x > 140 && x < 160
  1. An error: && does not accept vectors longer than 1
  2. [1] FALSE TRUE FALSE
  3. [1] FALSE
  4. [1] TRUE
Solution

Answer: An error: && does not accept vectors longer than 1

&& is for single-value conditions (in an if). With vectors you use &. Since R 4.3, mixing them gives an error, which is better than a silent wrong answer.

Question 3Short answer

What number does it print? Write just the number.

x <- c(130, 150, 170, 160)
sum(x > 140 & x < 165)
Solution

Answer: 2

x > 140 & x < 165 gives FALSE TRUE FALSE TRUE; sum counts the TRUEs: 150 and 160, two.

Question 4Single choice

What does this code print?

m <- matrix(1:6, nrow = 2)
apply(m, 2, sum)
  1. [1] 3 7 11
  2. [1] 9 12
  3. [1] 21
  4. [1] 1 2 3 4 5 6
Solution

Answer: [1] 3 7 11

matrix(1:6, nrow = 2) fills by columns: (1, 2), (3, 4), (5, 6). apply(m, 2, sum) adds up each column: 3, 7, 11.

Question 5Single choice

What shape does the result have?

f <- function(s) c(mean = 10, sd = s)
r <- sapply(c(1, 2, 3), f)
dim(r)
  1. [1] 2 3: 2 rows (mean, sd) and 3 columns
  2. [1] 3 2
  3. NULL: it is a list
  4. [1] 6
Solution

Answer: [1] 2 3: 2 rows (mean, sd) and 3 columns

Each call returns a vector of 2 elements; sapply binds them as columns: a 2 × 3 matrix. With t(r) you would have one row per value.

Question 6Single choice

What is wrong with this code?

ml <- c(150, 168, 142)
if (ml > 165) cat("Check the machine\n")
  1. Error: the condition has length greater than 1
  2. It prints “Check the machine”
  3. It prints nothing because the first cup is fine
  4. It prints the message three times
Solution

Answer: Error: the condition has length greater than 1

ml > 165 is three values. The fix is if (any(ml > 165)): “if any cup spills”.

Question 7Single choice

What does this code print? (Remember: qnorm(0.99) is 2.326.)

round(165 - qnorm(0.99) * 5, 1)
  1. [1] 153.4
  2. [1] 176.6
  3. [1] 164.9
  4. [1] 2.3
Solution

Answer: [1] 153.4

It is the mean that leaves 1 % above 165 if the standard deviation is 5: 165−z0.99⋅5 165 – z_{0.99} \cdot 5 .

Question 8Single choice

What is wrong with this code?

d <- data.frame(ml = c(150, 160), name = c("a", "b"))
apply(d, 1, function(f) f["ml"] + 1)
  1. Error: apply turns the data frame into a character matrix and it cannot be added to
  2. [1] 151 161
  3. [1] NA NA
  4. Nothing: apply does not work with data frames
Solution

Answer: Error: apply turns the data frame into a character matrix and it cannot be added to

With a text column, as.matrix(d) is a character matrix and "150" + 1 gives “non-numeric argument to binary operator”. To work with one column, use the vector directly: d$ml + 1.

Question 9True or false

With Var(X)=16 \mathrm{Var}(X) = 16 , Var(Y)=29 \mathrm{Var}(Y) = 29 and Cov(X,Y)=8 \mathrm{Cov}(X, Y) = 8 , mark true or false.

var_sum <- function(vx, vy, cxy = 0) vx + vy + 2 * cxy
  1. var_sum(16, 29, 8) returns 61.
  2. var_sum(16, 29) returns 61.
  3. sqrt(var_sum(16, 29, 8)) is the standard deviation of X + Y.
  4. If X and Y were independent, the covariance would be 1.
Solution
  • T — var_sum(16, 29, 8) returns 61.
  • F — var_sum(16, 29) returns 61.
  • T — sqrt(var_sum(16, 29, 8)) is the standard deviation of X + Y.
  • F — If X and Y were independent, the covariance would be 1.

16 + 29 + 2 · 8 = 61. Without the third argument, 0 is used and you get 45, the variance if they were independent (covariance 0, not 1).

Question 10Single choice

What does this code print?

x <- c(1, 2, 3, 4)
y <- c(2, 4, 6, 8)
cor(x, y)
  1. [1] 1
  2. [1] 2
  3. [1] 0.5
  4. [1] 3.33
Solution

Answer: [1] 1

The correlation measures the linear relationship, between −1 and 1. With Y=2X Y = 2X , all the points lie on an increasing line: 1.

Try it in the R playground

Paste this script into the R playground.

set.seed(8)
ml <- rnorm(2000, mean = 150, sd = 8)
status <- ifelse(ml < 140, "short", ifelse(ml > 165, "spill", "ok"))
round(prop.table(table(status)), 3)
round(c(short = pnorm(140, 150, 8), spill = 1 - pnorm(165, 150, 8)), 3)
hist(ml, breaks = 30, main = "2000 cups", xlab = "ml")
abline(v = c(140, 165), col = "red", lwd = 2)

What to look at:

  1. prop.table(table(status)) and the two pnorm give almost the same: the simulation confirms the model.
  2. The red lines on the histogram mark the two limits: what falls outside are the short cups and the ones that spill.
  3. Change sd = 8 to sd = 4 in the first two lines and run again: almost everything stays inside.
  4. In Environment, ml and status have 2000 elements: one line created each.

Cheat sheet: vectorizing in R

The essentials in 30 seconds: R’s operations already work on whole vectors (x * 2, x > 165, pnorm(x, …)); to decide element by element, ifelse with & and |; to apply your function to each value, sapply; to each row or column of a matrix, apply; if, && and ||, only with one value.

I want to…CodeResult
Classify into twoifelse(x > 165, "spill", "ok")character vector
Classify into threeifelse(x < a, "low", ifelse(x > b, "high", "ok"))character vector
Two conditions at oncex > a & x < blogical vector
Any / all?any(x > b), all(x > a)one TRUE or FALSE
Proportion that meets itmean(x > b)number
My function with several valuessapply(v, f)vector or matrix (one column per value)
By columns of a matrixapply(m, 2, mean)one value per column
Covariances and correlationscov(m), cor(m)matrices
P(X≤a) P(X \le a) / P(X>b) P(X > b) pnorm(a, mu, s) / 1 - pnorm(b, mu, s)probability
Value that leaves p p belowqnorm(p, mu, s)ml, minutes…
Time somethingsystem.time(expr)look at elapsed

Templates from the exercises: tune(sd) → mean =165−z0.99 σ = 165 – z_{0.99}\,\sigma and its p_short; total <- m[, 1] + m[, 2]; Var(X+Y)=VarX+VarY+2 Cov \mathrm{Var}(X + Y) = \mathrm{Var}X + \mathrm{Var}Y + 2\,\mathrm{Cov} .

SymptomLikely cause
“‘length = 12’ in coercion to ‘logical(1)'”&& or ` with vectors: use & or `
“the condition has length > 1”if with a vector: use any, all or ifelse
“non-numeric argument to binary operator” after applyapply on a data frame with text
The mean you compute comes out above the limitqnorm(risk) instead of qnorm(1 - risk)
The variance of a sum does not add upThe covariance is missing

Before you hand it in, ask yourself:

  1. Is there a loop that could be an operation on the whole vector?
  2. Have I used & and | in everything that works with vectors?
  3. Do my functions with qnorm look at the right tail?
  4. Have I compared the simulation with the theory?
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 R3: vectorization, normal and joint distributions =====================

# classify3(x, a, b): "low" (< a), "high" (> b) or "ok", without loops
classify3 <- function(x, a, b, labels = c("low", "ok", "high")) {
  stopifnot(is.numeric(x), a < b)
  ifelse(x < a, labels[1], ifelse(x > b, labels[3], labels[2]))
}

# prob_normal(a, b, mu, sd): P(X < a), P(a <= X <= b) and P(X > b) for a normal
prob_normal <- function(a, b, mu, sd, digits = 4) {
  stopifnot(sd > 0, a < b)
  pa <- pnorm(a, mu, sd); pb <- 1 - pnorm(b, mu, sd)
  round(c(below = pa, between = 1 - pa - pb, above = pb), digits)
}

# mean_for_risk(limit, sd, risk): mean that leaves 'risk' above 'limit'
mean_for_risk <- function(limit, sd, risk = 0.01) limit - qnorm(1 - risk) * sd

# joint_summary(m): means, standard deviations, covariances and correlations of the columns of m
joint_summary <- function(m, digits = 2) {
  m <- as.matrix(m)
  list(mean = round(apply(m, 2, mean), digits), sd = round(apply(m, 2, sd), digits),
       cov = round(cov(m), digits), cor = round(cor(m), digits))
}

# var_sum(vx, vy, cxy): theoretical variance of X + Y
var_sum <- function(vx, vy, cxy = 0) vx + vy + 2 * cxy
# Quick check with the coffee machine
prob_normal(140, 165, 150, 8)
round(mean_for_risk(165, 8), 2)
joint_summary(cups)$cor
var_sum(16, 29, 8)

Output:

  below between   above 
 0.1056  0.8640  0.0304 
[1] 146.39
       coffee milk
coffee   1.00 0.39
milk     0.39 1.00
[1] 61

joint_summary returns a list because each part has a different shape (vectors and matrices). With $cor, $cov… you take the one you need, and str(joint_summary(cups)) shows you the whole thing.

What next?

If apply, sapply or the difference between & and && still trip you up, go back to the block’s theory, R intensive 3: normal and joint distributions. And for pen-and-paper work with the normal and several variables, the ME1 transformations and joint distributions exercises.

The next block is R intensive 4: limit theorems and sampling: the Monte Carlo method to see the law of large numbers and the central limit theorem with your own eyes.

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

Next blockR intensive 4: limit theorems and sampling — The Monte Carlo method to see the law of large numbers and the central limit theorem with your own eyesBlock theory: ifelse, apply, sapply, pnorm and system.timeR intensive 3: normal and joint distributionsCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script