Transformations and joint distributions exercises — exam-style with R, a triangle, a joint mgf and a Jacobian (and the zero covariance that cost me a part)
In a practice exam in class I wrote in big letters that two variables were independent because their covariance was 0. It was the last part: I computed , got 0 and concluded “so they are independent”. One of the variables was the square of the other. The lecturer gave me zero for that part and, next to it, a drawing: a parabola. If one is the square of the other, knowing one you know the other; it’s just that the relationship isn’t a straight line, and covariance only sees straight lines.
These exercises follow the format of the ME1 EC2: one context per exercise, chained parts with their marks, calculations by hand and calculations with R. They are original, with the restaurant and the delivery from the transformations and joint distributions theory, and they go over what comes up most in the topic: the change of variable (and when it doesn’t work), a joint density on a triangle with its constant, marginals, conditionals and covariance, a joint mgf and a Jacobian. If a proof gets stuck, you have them step by step in the topic proofs.
Table of Contents
How to use this article
- Do the exercises with the exam in mind. In the ME1 EC2 you have 4 hours for 50 marks, with RStudio and the data open. These three exercises add up to 40 marks plus a 2.5 bonus: give them about 3 hours and 10 minutes.
- Paper for what is proved, R for what is computed. Results with 2 decimals, as the exam asks. Whatever you do in R, keep it in a script: at the end of the exam you have to upload the
.Rfile with the code for each exercise. - Draw the support before every double integral. Thirty seconds with a pencil give you the limits and tell you whether there can be independence.
- Mark yourself with the criteria. Each solution comes with “How it is marked” with a split of the marks. It is a guide, mine: it is not the official marking scheme.
- Finish with the cheat sheet and “For your script”. The cheat sheet only has results (it is what you can take, handwritten: two sheets, both sides, in the EC2) and “For your script” is the topic’s code ready for your
.Rfile. If you want to revise with the computer first, the R practice has the topic’s three programs with comments.
Exercise 1: the speed score (10 marks)
The restaurant gives each order a “speed score” based on the kitchen time , in minutes, which follows an : the score is (1 if the kitchen is instantaneous, close to 0 if it takes ages).
(a) Find the support and the density of with the change of variable theorem, justifying that it can be used. What known distribution is it? (3 marks)
(b) Write in terms of the distribution function of and explain why the result of (a) is not a coincidence. (2 marks)
(c) Let . Get its density with the distribution function method and compute . (2 marks)
(d) With R, simulate 10,000 kitchen times from runif (without rexp), compute and , check and and draw the histogram of with its density on top. (3 marks)
In (a), solve for in terms of and look at the sign of the derivative. In (d), the inverse of the exponential’s gives you the kitchen time from a uniform number.
Exercise 2: rush hour in half-hours (15 marks)
At rush hour, the restaurant measures times in half-hours. Let be the moment the order leaves the kitchen and the moment it arrives, both in half-hours from the order. Their joint density is
and 0 elsewhere.
(a) Find so that is a density. (2 marks)
(b) Get the marginal densities and . (3 marks)
(c) Compute the probability that the delivery lasts more than a quarter of an hour, . (2 marks)
(d) Get the conditional density and . If the order arrived at 27 minutes (), when do you expect it left the kitchen? (3 marks)
(e) Compute and the correlation coefficient. Are and independent? Justify it. (3 marks)
(f) With R, check the value of and the probability in (c) with double integrals. (2 marks)
Draw the triangle . For , goes from to 1; for , goes from 0 to . In (c), the region is the strip above the line .
Exercise 3: the big order (15 marks)
Group orders take longer in the kitchen: the kitchen time is minutes, and the delivery, minutes, independent of the kitchen. Let be the total time.
(a) Write the joint density of and compute its joint moment generating function. (3 marks)
(b) Using the joint mgf, find the distribution of and compute with R the probability that the order takes more than 20 minutes. (3 marks)
(c) Compute and the correlation coefficient between and . (2 marks)
(d) Let , the fraction of the time spent in the kitchen. Get the joint density of with its support and its marginals, and say whether and are independent. (5 marks)
(e) With R, simulate 10,000 big orders and check , the correlation between and and the histogram of with its density. (2 marks)
In (b), means . In (d), it is the theory’s order Jacobian with another density: , , .
Bonus (2.5 marks)
The error in the time the app estimates is minutes. Let . Prove that (1 mark) and that, however, and are not independent (1.5 marks).
Solutions
Exercise 1
(a) takes values in , so takes values in . The function is differentiable and strictly decreasing (): the theorem can be used. The inverse:
: the speed score is uniform.
Why the absolute value isn’t decoration. is decreasing, so is negative. Without the absolute value you’d get : a negative “density”, which can’t be. And notice the order: first the support, then the calculation. Without knowing that lives in , the 1 you get tells you nothing; with the support, it’s a uniform you recognise at once.
How it is marked: support (0.5), justifying that is monotonic and differentiable (0.5), inverse and derivative (1), density with the absolute value (0.5) and identifying it (0.5).
(b) , so . By the probability integral transform, for any continuous variable, and if is uniform, so is . The result of (a) is a particular case of .
Check you’ve got it: if the kitchen time were an and the speed score were still , would it still be uniform?
No. Now , which isn’t the speed score, so the shortcut from (b) no longer works. With the distribution function method: , and differentiating, on : a . For example, , not 0.30. The uniform only comes out when the speed score is exactly .
How it is marked: writing (1) and quoting with the step to (1).
(c) is increasing on , but the question asks for the method. For :
Check without : , and .
Why the distribution function method doesn’t need monotonicity. The theorem needs a monotonic ; the distribution function method only needs you to translate the event into an event about , and that can always be done. The delicate step is : it holds because both sides are positive, and that’s why we ask for .
Writing . That’s solving the wrong way round. Check it with a number: is , not .
How it is marked: (0.75), derivative (0.75) and probability (0.5).
(d)
set.seed(2026) x <- -10 * log(runif(10000)) # the inverse of F: -10 log(1 - u), and 1 - U is also uniform s <- exp(-0.1 * x) # speed score y <- sqrt(x) round(c(mean(s <= 0.3), 0.3), 4) round(c(mean(y > 4), exp(-1.6)), 4) hist(y, freq = FALSE, breaks = 30, main = "Square root of the kitchen time") curve(0.2 * x * exp(-0.1 * x^2), add = TRUE, col = "red", lwd = 2)
Output:
[1] 0.2997 0.3000 [1] 0.2007 0.2019
The proportion of scores below 0.3 is 0.30, that of a uniform, and that of roots greater than 4, 0.20, as in (c). In the drawing, the histogram of follows the curve : it rises from 0, peaks near and falls with a short tail.
How it is marked: simulating with runif and the inverse (1), the two checks (1) and the histogram with the curve (1).
Exercise 2
The plan, before the first integral. The whole exercise lives in the same triangle, , so the first thing is to draw it: an order can’t arrive before it leaves the kitchen. Each part is a piece of that drawing: (a) the whole triangle, (b) a vertical slice for and a horizontal one for , (c) the small triangle in the top left corner and (d) the slice at height .
Integrating over the square . You get , a number so clean nobody suspects it, and everything else in the exercise ends up wrong by a factor of 2.
(a) The integral over the triangle must be 1. For each , goes from 0 to :
How it is marked: the triangle’s limits (1) and the calculation (1).
(b)
Check: and . is a .
How it is marked: 1.5 for each marginal (limits 0.5, calculation 0.75 and support 0.25).
(c) . That line only cuts the triangle if , and for each , goes from to 1:
The inner integral: . 25 % of the orders spend more than a quarter of an hour on delivery.
Why the outer integral only goes up to 1/2. The region is the small triangle with vertices , and : if , the line goes above 1 and there’s no room left for . The obvious move would be to let run from 0 to 1, but then the inner integral would have its lower limit above its upper one and would subtract instead of add. With on the outside, from 1/2 to 1, and from 0 to , you also get : if the two orders don’t agree, one of the limits is wrong.
How it is marked: drawing or describing the region (0.5), limits (0.75) and calculation (0.75).
(d)
With : half-hours, that is, at 15 minutes. More than half of 0.9: since the density grows with , late kitchen exits weigh more.
Why the triangle is sliced at height . Conditioning on means keeping the horizontal line at that height: on it, goes from 0 to , not from 0 to 1. Over that slice, doesn’t add up to 1, and that’s why you divide by : , exactly the value of .
Check you’ve got it: if the order arrived after 18 minutes, when do you expect it left the kitchen?
18 minutes is half-hours. half-hours, that is, after 10 minutes. The slice is shorter (from 0 to 0.6), but the proportion is the same: of the way.
How it is marked: conditional with its support (1), integral (1.5) and value at 0.9 with its reading (0.5).
(e) With the marginals:
For : , ; , .
They are not independent: the support is a triangle (if , can’t be 0.5), or, with numbers, and . The non-zero covariance also proves it (independent ⇒ covariance 0), but here it wasn’t needed.
Why look at the support before the covariance. If fixing changes the possible values of , they can’t be independent, with no calculation at all. The covariance only works one way: non-zero proves dependence, but zero proves nothing (that’s the bonus).
Computing as . That already assumes they’re independent, and the covariance comes out 0 whatever you do. is integrated with the joint density, over the triangle.
How it is marked: , and (1.5), covariance and correlation (1) and the justification of dependence (0.5).
(f)
f <- function(x, y) (x + y) * (x < y) # without the K inner <- function(x) integrate(function(y) f(x, y), x, 1)$value 1 / integrate(Vectorize(inner), 0, 1)$value # K g <- function(x) integrate(function(y) 2 * f(x, y), x + 0.5, 1)$value integrate(Vectorize(g), 0, 0.5)$value # P(Y - X > 1/2)
Output:
[1] 2 [1] 0.25
2 and 0.25, as by hand. Look at the limits of the second one: the outer one only goes up to 0.5, because for the strip falls outside the triangle.
How it is marked: each check with Vectorize and the triangle’s limits (1 + 1).
Exercise 3
(a) By independence, the joint density is the product of the marginals:
And the joint mgf, also by independence, is the product of the mgfs (topic 4):
How it is marked: joint density with support (1) and mgf with the justification of independence (2).
(b) , the mgf of a . Since the mgf determines the distribution, , with a mean of 15 minutes.
1 - pgamma(20, shape = 3, rate = 0.2)
Output:
[1] 0.2381033
0.24: almost one in four big orders takes more than 20 minutes.
Why the mgf and not an integral. The obvious route for a sum is the convolution, . With the mgf everything is a product: both have the same base , so the exponents add up, . That works because the kitchen and the delivery have the same parameter 0.2: with an delivery, the product wouldn’t be the mgf of any gamma.
How it is marked: (1), identifying the gamma (1) and the probability (1).
(c) With the covariance property and the independence of and :
How it is marked: covariance (1) and correlation (1).
(d) Support: and . Inverse: , , with and .
The first bracket is the density of a () and the second, that of a .
(The second integral: .) , , and since on a rectangular support, they are independent. In the big order, the kitchen takes on average of the time, and that doesn’t depend on whether the order took long or not.
The plan for (d), before the Jacobian. Four steps, and each one earns marks: the new support, the inverse, the Jacobian and substituting. The inverse comes from reading the definitions backwards: if , the kitchen is and the delivery is what’s left, . When you substitute, the exponential becomes because : that’s where disappears, and that’s why the density splits into a piece in times a piece in .
Check you’ve got it: why is the support of a rectangle here when in exercise 2 it was a triangle?
Because any pair works: for any and any in , and are positive, so it’s a possible order. In exercise 2, knowing limits : if , can’t go above 0.2. Factorising the density isn’t enough: you also need a rectangular support.
How it is marked: support (0.5), inverse and Jacobian (1.5), joint density (1), marginals (1.5) and independence (0.5).
(e)
set.seed(2026) x <- rgamma(10000, 2, 0.2); r <- rexp(10000, 0.2) t <- x + r; u <- x / t round(c(mean(u > 0.5), 1 - 0.5^2), 4) # P(U > 1/2) = 1 - F(1/2) = 3/4 round(cor(t, u), 3) hist(u, freq = FALSE, breaks = 20, main = "Kitchen fraction") curve(2 * x, from = 0, to = 1, add = TRUE, col = "red", lwd = 2)
Output:
[1] 0.7543 0.7500 [1] 0.007
0.75 simulated (0.7543) against theoretical (the of the beta(2, 1) is ), and a correlation of practically 0. In the drawing, the histogram rises in a straight line following : high kitchen fractions are more frequent than low ones.
How it is marked: the simulation with and the correlation (1) and the histogram with the line (1).
Bonus
and, since the density of is symmetric about 0, (the integral of an odd function over the whole line). Then
For dependence, one event where the joint distribution doesn’t factorise is enough. If , then , so
(.) They are not independent: zero covariance does not imply independence. It is my anecdote from the beginning.
How it is marked: by symmetry (1) and an event that doesn’t factorise, with numbers (1.5).
What’s wrong here?
Three classmates’ solutions with one mistake each. Before reading the explanation, look for the slip.
Fragment 1. “In exercise 2, the marginal of is , for .”
integrate(function(y) 1 + 2 * y, 0, 1)
Output:
2 with absolute error < 2.2e-14
It integrates to 2: it isn’t a density. The limits are those of the square , not of the triangle. For a fixed , only goes up to : the right marginal is .
Integrate your marginal before going on. If it doesn’t give 1, the mistake is in the limits, and in the drawing you see it straight away: the horizontal line at height leaves the triangle at , not at .
Fragment 2. “In the order, is the kitchen and the arrival, with and . Then .”
set.seed(2026) x <- rexp(1e5, 0.1); y <- x + rexp(1e5, 0.1) round(c(var(x + y), var(x) + var(y), var(x) + var(y) + 2 * cov(x, y)), 1)
Output:
[1] 499.8 300.3 499.8
The real variance of is about 500, not 300. Adding variances only works with independent (or uncorrelated) variables, and and have covariance 100: is missing.
“the variance of a sum is the sum of the variances” without checking whether they are independent. When one variable is built from the other (like the arrival from the kitchen), they never are.
Fragment 3. “If and , with and , by the change of variable theorem , .”
integrate(function(y) 1 / (4 * sqrt(y)), 0, 1)
Output:
0.5 with absolute error < 1.4e-15
It integrates to 0.5: half is missing. isn’t monotonic on and the theorem can’t be used. With the distribution function, , and : double, because each comes from and from .
Before the theorem, one question: does each come from a single ? If it comes from two, use the method.
Practice quiz
Before moving on to the next topic, check you have got it. This quiz is here to consolidate what this article explains: the ME1 exam is not a multiple-choice test (you solve problems by hand and with R), so no mark here counts. There are 10 questions on transformations and joint distributions: key ideas, typical mistakes and many «what does this R code print?», with the outputs from really running it. In the short answers, a decimal point or a decimal comma both work. Answer without running anything, press Check and read the explanation for each option; you can repeat it as many times as you like.
The joint density is f(x, y) = 2(x + y) on the triangle 0 < x < y < 1. A classmate works out Y’s marginal by integrating x from 0 to 1 and gets 1 + 2y, which integrates to 2. What did they do wrong?
- They used the square’s limits: for a fixed y, x only goes up to y
- They should have integrated y instead of x
- A joint density cannot be integrated
- Integrating to 2 is normal for a marginal
Solution
Answer: They used the square’s limits: for a fixed y, x only goes up to y
Integrate your marginal before moving on. If it does not give 1, the mistake is in the limits, and the support drawing shows it at once.
X is the cooking time and Y = X + R the order’s arrival time. With Var(X) = 100 and Var(Y) = 200, a classmate says Var(X + Y) = 300. What is wrong?
- X and Y are not independent (Y is built from X): 2·Cov(X, Y) = 200 is missing, and the real variance is about 500
- Nothing: the variance of a sum is always the sum of the variances
- They should subtract the covariance
- Var(X + Y) = Var(X) · Var(Y)
Solution
Answer: X and Y are not independent (Y is built from X): 2·Cov(X, Y) = 200 is missing, and the real variance is about 500
Var(X + Y) = Var(X) + Var(Y) + 2·Cov(X, Y). The article’s simulation gives 499.8 against 300.
X ~ U(−1, 1) and Y = X². A classmate applies the change-of-variable theorem with x = √y and gets f_Y(y) = 1/(4√y), which integrates to 0.5. Why?
- x² is not monotonic on (−1, 1): two values of x (√y and −√y) reach each y, and the theorem does not apply
- They differentiated √y wrongly
- The uniform on (−1, 1) has density 1, not 1/2
- Y = X² has no density
Solution
Answer: x² is not monotonic on (−1, 1): two values of x (√y and −√y) reach each y, and the theorem does not apply
Before the theorem, one question: does a single x reach each y? If two do, use the distribution-function method.
What number does it print? (Ignore the second part of integrate‘s output: write just the number.)
integrate(function(y) 1 / (2 * sqrt(y)), 0, 1)$value
Solution
Answer: 1
f_Y(y) = 1/(2√y) on (0, 1) is a density: it integrates to 1. 1/(4√y) integrated to 0.5, the clue that half was missing.
With E(X) = 0.4167, E(Y) = 0.75 and E(XY) = 0.3333, what is Cov(X, Y)? (4 decimals.)
round(0.3333 - 0.4167 * 0.75, 4)
Solution
Answer: 0.0208
Cov(X, Y) = E(XY) − E(X)E(Y) = 0.3333 − 0.3125 = 0.0208. Positive: when X is large, Y tends to be large too.
You get Cov(X, Y) = 0. Can you claim that X and Y are independent?
- No: covariance 0 only says they are uncorrelated; independence is proved with the joint density (or the mgf)
- Yes: covariance 0 and independence are the same thing
- Yes, if the means are also positive
- No, because the covariance can never be 0
Solution
Answer: No: covariance 0 only says they are uncorrelated; independence is proved with the joint density (or the mgf)
It is the article’s anecdote («the zero covariance that cost me a part») and the fourth question of «Before handing in».
Match each step with how it is done, for a joint density f(x, y):
| Marginal of X | |
| Conditional of Y given X = x | |
| Covariance | |
| Correlation |
Definitions:
- Cov(X, Y) / (σ_X σ_Y)
- f(x, y) / f_X(x)
- E(XY) − E(X)E(Y)
- f_X(x) + f_Y(y)
- Integrate f over y, with the support's limits for each x
Solution
- Marginal of X → Integrate f over y, with the support’s limits for each x
- Conditional of Y given X = x → f(x, y) / f_X(x)
- Covariance → E(XY) − E(X)E(Y)
- Correlation → Cov(X, Y) / (σ_X σ_Y)
First of all, draw the support: the limits of every integral come from it.
True or false?
- If g is monotonic, f_Y(y) = f_X(g⁻¹(y)) · |(g⁻¹)'(y)|.
- Every density given in the exam comes with its support.
- E(XY) = E(X)E(Y) for any pair of variables.
- The correlation is always between −1 and 1.
Solution
- T — If g is monotonic, f_Y(y) = f_X(g⁻¹(y)) · |(g⁻¹)'(y)|.
- T — Every density given in the exam comes with its support.
- F — E(XY) = E(X)E(Y) for any pair of variables.
- T — The correlation is always between −1 and 1.
E(XY) = E(X)E(Y) holds for independent (or uncorrelated) variables; in general E(XY) must be computed from the joint density.
A discrete variable takes values with probabilities 0.4, 0.4 and 0.2. What does it print?
sum(c(0.4, 0.4, 0.2))
Solution
Answer: 1
It is the marginal pX from the dishes-and-drinks table: adding up the joint’s rows gives the marginal, and a marginal always adds up to 1. It is the first check after getting it.
Put in order the steps to get the density of Y = g(X) when g is not monotonic:
- Check that f_Y integrates to 1
- Write F_Y(y) = P(g(X) ≤ y)
- Rewrite the event in terms of X (for example, −√y ≤ X ≤ √y)
- Differentiate F_Y to get f_Y and write its support
- Work out that probability with X’s distribution
Solution
Correct order:
- Write F_Y(y) = P(g(X) ≤ y)
- Rewrite the event in terms of X (for example, −√y ≤ X ≤ √y)
- Work out that probability with X’s distribution
- Differentiate F_Y to get f_Y and write its support
- Check that f_Y integrates to 1
It is the distribution-function method, the one that always works. The final check with integrate catches limit mistakes.
Try it in the R playground
Open the site’s R playground (or RStudio) and paste this script. It is the whole of exercise 2, plus a simulation of the triangle that isn’t in the solutions:
f <- function(x, y) 2 * (x + y) * (x < y) double_int <- function(g) integrate(Vectorize(function(x) integrate(function(y) g(x, y) * f(x, y), x, 1)$value), 0, 1)$value EX <- double_int(function(x, y) x); EY <- double_int(function(x, y) y); EXY <- double_int(function(x, y) x * y) VX <- double_int(function(x, y) x^2) - EX^2; VY <- double_int(function(x, y) y^2) - EY^2 round(c(EX = EX, EY = EY, cov = EXY - EX * EY, rho = (EXY - EX * EY) / sqrt(VX * VY)), 4) # Simulating the triangle by acceptance: random points in the square, keep some of them set.seed(1); n <- 2e5 x <- runif(n); y <- runif(n); w <- runif(n, 0, 4) # 4 is the maximum of f accept <- w < f(x, y) xs <- x[accept]; ys <- y[accept] round(c(mean(xs), mean(ys), cor(xs, ys), mean(ys - xs > 0.5)), 3) plot(xs[1:500], ys[1:500], pch = 20); abline(0, 1, col = "red")
What to look at:
- The moments in the first line are those of solution (e): , , and 0.44.
- The acceptance simulation gives almost the same without a single integral: it is another way of checking a result when you don’t trust the limits.
- In the cloud, the points pile up at the top right, where is large and the density, high. None is below the diagonal.
Cheat sheet: transformations and joint distributions
The essentials in 30 seconds. One variable: if is monotonic, ; if not, and differentiate. Two variables: draw the support, integrate out the extra one for the marginal, divide for the conditional, and covariance .
| I want… | Formula |
|---|---|
| Density of , monotonic | |
| Density of , not monotonic | , differentiate |
| , with | |
| Uniforms and any | ; |
| Marginal | (support’s limits) |
| Conditional | |
| Law of total expectation | |
| Law of total variance | |
| Independence | at every point (rectangular support) |
| of a sum | , always |
| of a product | if they are independent |
| Covariance | ; |
| Correlation | , |
| Variance of | |
| Joint mgf | ; ; |
| mgf of | ; with independence, |
| Sum of gammas, same | |
| Jacobian | , of the inverse |
| with independent gammas, same | , independent of |
| Bivariate normal: marginal | |
| Bivariate normal: conditional |
| Symptom | Likely cause |
|---|---|
| The marginal doesn’t integrate to 1 | Rectangle limits on a triangular support |
| The density of integrates to 0.5 | Only one root: wasn’t monotonic |
| Negative density | Missing absolute value of the Jacobian or the derivative |
| Mistake in or in a variance | |
length(lower) == 1 is not TRUE or result of wrong length | Missing Vectorize in the outer integral |
Before handing in, ask yourself:
- Have I written the support of every density I have given?
- Does every density I got integrate to 1?
- If I used or added variances, were they independent?
- If I say “independent”, have I proved it with the joint density or the mgf, and not with the covariance?
For your script
The topic’s code, commented and tested, to copy into your exam .R file. They are short functions: you give them the density or the data from the question and they return the result.
# ---------- Transformations and joint distributions (ME1, topic 6) ----------
# Double integral of f(x, y) with x between a and b, and y between ylo(x) and yhi(x) (limits depending on x)
# (don't call an argument c: you would hide R's c() function)
double_int <- function(f, a, b, ylo, yhi) integrate(Vectorize(function(x)
integrate(function(y) f(x, y), ylo(x), yhi(x))$value), a, b)$value
# Constant K: f0 is the density WITHOUT the K
constant <- function(f0, a, b, ylo, yhi) 1 / double_int(f0, a, b, ylo, yhi)
# Marginals at a point (support's limits, as functions)
marg_x <- function(f, x, ylo, yhi) integrate(function(y) f(x, y), ylo(x), yhi(x))$value
marg_y <- function(f, y, xlo, xhi) integrate(function(x) f(x, y), xlo(y), xhi(y))$value
# Moments, covariance and correlation from the joint density
moments <- function(f, a, b, ylo, yhi) {
E <- function(g) double_int(function(x, y) g(x, y) * f(x, y), a, b, ylo, yhi)
EX <- E(function(x, y) x); EY <- E(function(x, y) y); EXY <- E(function(x, y) x * y)
VX <- E(function(x, y) x^2) - EX^2; VY <- E(function(x, y) y^2) - EY^2
round(c(EX = EX, EY = EY, EXY = EXY, cov = EXY - EX * EY, rho = (EXY - EX * EY) / sqrt(VX * VY)), 4)
}
# Discrete joint table: marginals, covariance, correlation and independence
joint_table <- function(p, xv, yv) {
pX <- rowSums(p); pY <- colSums(p)
EX <- sum(xv * pX); EY <- sum(yv * pY); EXY <- sum(outer(xv, yv) * p)
VX <- sum(xv^2 * pX) - EX^2; VY <- sum(yv^2 * pY) - EY^2
list(pX = pX, pY = pY, cov = EXY - EX * EY, rho = (EXY - EX * EY) / sqrt(VX * VY),
independent = isTRUE(all.equal(c(p), c(outer(pX, pY)))))
}
# Check a transformation by simulation: histogram of g(x) with the proposed density
check_change <- function(x, g, fY, ...) {
y <- g(x); hist(y, freq = FALSE, breaks = 40, main = "Change of variable", ...)
curve(fY(x), add = TRUE, col = "red", lwd = 2, n = 400)
}
# Bivariate normal: density and conditional Y | X = x
dbiv <- function(x, y, mx, my, sx, sy, rho) {
q <- ((x - mx) / sx)^2 + ((y - my) / sy)^2 - 2 * rho * (x - mx) * (y - my) / (sx * sy)
exp(-q / (2 * (1 - rho^2))) / (2 * pi * sx * sy * sqrt(1 - rho^2))
}
cond_biv <- function(x, mx, my, sx, sy, rho) c(mean = my + rho * sy / sx * (x - mx), sd = sy * sqrt(1 - rho^2))
# ---------- Examples (the exercises in this article) ----------
f2 <- function(x, y) 2 * (x + y) * (x < y)
one <- function(x) 1; zero <- function(x) 0; id <- function(x) x
round(constant(function(x, y) (x + y) * (x < y), 0, 1, id, one), 2) # ex. 2 (a): K = 2
round(double_int(f2, 0, 0.5, function(x) x + 0.5, one), 2) # ex. 2 (c): 0.25
moments(f2, 0, 1, id, one) # ex. 2 (e)
round(1 - pgamma(20, 3, 0.2), 2) # ex. 3 (b)
p <- matrix(c(0.20, 0.15, 0.05, 0.10, 0.20, 0.10, 0.02, 0.08, 0.10), 3, byrow = TRUE)
str(joint_table(p, 1:3, 0:2)) # dishes and drinks
round(cond_biv(5, 3, 15, 1, 4, 0.8), 2) # R | D = 5
Output:
[1] 2
[1] 0.25
EX EY EXY cov rho
0.4167 0.7500 0.3333 0.0208 0.4402
[1] 0.24
List of 5
$ pX : num [1:3] 0.4 0.4 0.2
$ pY : num [1:3] 0.32 0.43 0.25
$ cov : num 0.216
$ rho : num 0.384
$ independent: logi FALSE
mean sd
21.4 2.4
double_int is the one that pays off most: you give it the density, the limits of and those of as functions of (id is , one is ), and you don’t have to write the Vectorize in the exam. With it you get , the 0.25 in (c) and the moments in (e) with the correlation 0.44. joint_table does the whole discrete part at once (the dishes and drinks table gives covariance 0.216, correlation 0.38 and independent = FALSE), and cond_biv returns the mean and standard deviation of the conditional of the bivariate normal: 21.4 and 2.4.
What comes next?
With two variables at once you can already work with a sum of many. The next ME1 topic is inequalities and limit theorems: Chebyshev’s inequality, the law of large numbers and the central limit theorem, which explain why the mean of many orders looks like a normal even though each time is exponential.
If you want to revise first, you have the theory, the proofs and the practice for this topic, and the normal distribution, where the bivariate normal and the come from.
Keep goingAll Statistics articlesDid this article help you? Here is how you can support SergioLearns →
Ready for the exam?ME1 EC2 mock exam — 4 hours with R beside you, from the normal to confidence intervals, four versions and a mark out of 50 (and why exercise 1 is worth double)


