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.
Table of Contents
How to use this article
- Open the R playground (or RStudio). Each exercise sets its seed: with the same order of commands, you will get the same numbers.
- Level 1, reproduce and read; level 2, write a function that uses
qnormandpnormand apply it to several cases withsapply; level 3, a full problem in the format of the ME1 exam script. - The solutions are folded, with the reason for every decision.
- Finish with the 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)
- How many of the 12 cups spill and how many are short?
- Why are there two
ifelse, one inside the other? - What proportion of cups does the model expect to be short, and what proportion to spill? Does it match the 12 cups?
- What does the 163.16 from
qnormmean?
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 , the mean to programme is the one that leaves 1 % above 165 ml: .
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, ml, and then the milk, which a sensor adjusts to the coffee that came out: , with independent of . The cup’s total is .
- a) (3 points) With
set.seed(30), simulate 10,000 cups and store them in a two-column matrixcups(coffee,milk). Give its dimension and, withapply, 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
totalwithout loops, its simulated mean and variance, and compare them with the theoretical ones: and . Estimate by simulation and withpnorm. - d) (4 points) For a million cups of , label each one
"spill"or"ok"in two ways: with aforloop and anif, and withifelse. Time both withsystem.timeand 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.
| Question | Look at… | Command | Why |
|---|---|---|---|
| How many spill and how many are short | the 12 cups | table(status) | it’s counting what came out; the model plays no part here |
Why two ifelse | the code | one ifelse inside another | there are three categories and each ifelse can only split in two |
| What proportion the model expects | the normal | pnorm(140, …) and 1 - pnorm(165, …) | pnorm gives the area to the left; spilling means landing to the right of 165 |
| What the 163.16 is | the normal | qnorm(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
- 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.
- Because there are three categories. The first
ifelseseparates the short ones from the rest; for the rest, the “no” is anotherifelsethat 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
- 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.
- It is the 95th percentile: 95 % of the cups carry 163.16 ml or less. Notice that
1 - pnorm(…)andqnorm(…)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 . 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:
| Step | Working | Why |
|---|---|---|
| 1. What’s asked | at most 1 % of cups above the rim | |
| 2. Standardise | subtracting the mean and dividing by turns any normal into the standard one | |
| 3. Quantile | the value that leaves 1 % to the right leaves 99 % to the left: qnorm(0.99) | |
| 4. Solve | it’s the formula in the statement, with numbers | |
| 5. The short ones | , 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
How to read it: with a machine of 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 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 notqnorm(risk). The 1 % that spills is on the right;qnorm(0.01)gives 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. sapplyinstead of a loop. It callstunewith 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_shortchanges 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:
The mean has vanished: once you fix the 1 % of spills, dictates it. The 25 ml are the gap between 140 and 165. With , and the area to the left is practically zero; with , 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 standard deviations: . 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, gives the standard deviation, so .
| What | Working | Why |
|---|---|---|
| the expectation of a sum is the sum, dependent or not | ||
| the 90 doesn’t vary; multiplying by 0.5 multiplies the variance by ; the noise is independent and adds its own | ||
| the only part of that covaries with is ; the noise contributes 0 | ||
| 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 ? 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: .
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
The covariance is positive (8.44; the theoretical one is ) 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 .
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 : forget the covariance and you would say 45, and the standard deviation would be 6.71 instead of 7.81. : 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, : and , so and the standard deviation is . 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.
What does this code print?
x <- c(130, 150, 170) ifelse(x > 160, "high", "ok")
[1] "ok" "ok" "high"[1] "high"[1] "ok"- 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.
What happens when you run this in R 4.3 or later?
x <- c(130, 150, 170) x > 140 && x < 160
- An error:
&&does not accept vectors longer than 1 [1] FALSE TRUE FALSE[1] FALSE[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.
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.
What does this code print?
m <- matrix(1:6, nrow = 2) apply(m, 2, sum)
[1] 3 7 11[1] 9 12[1] 21[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.
What shape does the result have?
f <- function(s) c(mean = 10, sd = s) r <- sapply(c(1, 2, 3), f) dim(r)
[1] 2 3: 2 rows (mean, sd) and 3 columns[1] 3 2NULL: it is a list[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.
What is wrong with this code?
ml <- c(150, 168, 142)
if (ml > 165) cat("Check the machine\n")- Error: the condition has length greater than 1
- It prints “Check the machine”
- It prints nothing because the first cup is fine
- 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”.
What does this code print? (Remember: qnorm(0.99) is 2.326.)
round(165 - qnorm(0.99) * 5, 1)
[1] 153.4[1] 176.6[1] 164.9[1] 2.3
Solution
Answer: [1] 153.4
It is the mean that leaves 1 % above 165 if the standard deviation is 5: .
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)- Error:
applyturns the data frame into a character matrix and it cannot be added to [1] 151 161[1] NA NA- Nothing:
applydoes 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.
With , and , mark true or false.
var_sum <- function(vx, vy, cxy = 0) vx + vy + 2 * cxy
var_sum(16, 29, 8)returns 61.var_sum(16, 29)returns 61.sqrt(var_sum(16, 29, 8))is the standard deviation of X + Y.- 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).
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] 0.5[1] 3.33
Solution
Answer: [1] 1
The correlation measures the linear relationship, between −1 and 1. With , 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:
prop.table(table(status))and the twopnormgive almost the same: the simulation confirms the model.- The red lines on the histogram mark the two limits: what falls outside are the short cups and the ones that spill.
- Change
sd = 8tosd = 4in the first two lines and run again: almost everything stays inside. - In Environment,
mlandstatushave 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… | Code | Result |
|---|---|---|
| Classify into two | ifelse(x > 165, "spill", "ok") | character vector |
| Classify into three | ifelse(x < a, "low", ifelse(x > b, "high", "ok")) | character vector |
| Two conditions at once | x > a & x < b | logical vector |
| Any / all? | any(x > b), all(x > a) | one TRUE or FALSE |
| Proportion that meets it | mean(x > b) | number |
| My function with several values | sapply(v, f) | vector or matrix (one column per value) |
| By columns of a matrix | apply(m, 2, mean) | one value per column |
| Covariances and correlations | cov(m), cor(m) | matrices |
| / | pnorm(a, mu, s) / 1 - pnorm(b, mu, s) | probability |
| Value that leaves below | qnorm(p, mu, s) | ml, minutes… |
| Time something | system.time(expr) | look at elapsed |
Templates from the exercises: tune(sd) → mean and its p_short; total <- m[, 1] + m[, 2]; .
| Symptom | Likely 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 apply | apply on a data frame with text | |||
| The mean you compute comes out above the limit | qnorm(risk) instead of qnorm(1 - risk) | |||
| The variance of a sum does not add up | The covariance is missing |
Before you hand it in, ask yourself:
- Is there a loop that could be an operation on the whole vector?
- Have I used
&and|in everything that works with vectors? - Do my functions with
qnormlook at the right tail? - Have I compared the simulation with the theory?
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


