Transformations and joint distributions in R — practice with runif, integrate inside integrate and the bivariate normal of the delivery (and the Vectorize I was missing)

The night before the joint distributions lab session, R answered length(lower) == 1 is not TRUE to my first double integral. I wanted to check that the density of the order integrated to 1 and had written one integral inside another. My lower limit didn’t have length 1? I had given it an x, a number. I tried changing the limits, writing Inf another way, restarting RStudio… Half an hour later I found that the problem wasn’t in the density, but in how integrate calls the outer function: it passes it many points at once, so my x was a vector of 21 numbers, and my function only knew how to compute one. It is fixed with one word, Vectorize, and it is the first thing you will see fail (and fix) in this practice.

This is the R practice for transformations and joint distributions: three programs that do with the computer what the theory and the proofs do on paper. The first simulates the kitchen and the delivery with runif and checks two transformations; the second works with the joint density of the order using integrate and compares it with a simulation; the third, with the table of dishes and drinks and with the bivariate normal of the distance and the delivery time. Every output, explained number by number.

Before we start

  • The three programs can be pasted as they are into the site’s R playground or into RStudio. They only use base R: nothing to install.
  • The simulations use set.seed(2026): if you copy it the same, you get the same numbers as here.
  • The example is the one for the whole topic: the kitchen X X and the delivery R R , independent and exp⁡(0.1) \exp(0.1) (10 minutes on average each), and the arrival minute Y=X+R Y = X + R . In program 1 the delivery is modelled differently, with the rider’s speed.
  • Results with 2 decimals, as in the exam (round(x, 2)); small probabilities with 3 or 4.

Program 1: kitchens made with runif and the rider’s bike

The idea

Two transformations from the theory, checked with 10,000 orders:

  1. The inverse of F F : if U∼U(0,1) U \sim U(0, 1) , −10log⁡(1−U)∼exp⁡(0.1) -10\log(1 – U) \sim \exp(0.1) . We make kitchen times without using rexp.
  2. The change of variable: with the speed V∼U(12,20) V \sim U(12, 20) km/h and a 3 km trip, the delivery R=180/V R = 180/V has density 22.5/r2 22.5/r^2 on (9,15) (9, 15) .

If the calculations are right, the histograms must follow the curves.

Put into words, program 1 makes times in two ways. The kitchen time comes from a random number between 0 and 1, which acts as a percentile (“70 % of kitchen times are shorter than this one”), and the inverse of F F turns it into minutes. The delivery comes from the speed: the time is 180 divided by it. In both cases, if the maths is right, you answer the same way: lots of data, a histogram and the curve on top.

Where 22.5/r² comes from, step by step

The delivery density comes out in five steps:

StepCalculationWhy
Supportv=20⇒r=180/20=9 v = 20 \Rightarrow r = 180/20 = 9 ; v=12⇒r=180/12=15 v = 12 \Rightarrow r = 180/12 = 15 180/v 180/v goes down when v v goes up: the fastest bike gives the shortest delivery
DistributionFR(r)=P(180/V≤r)=P(V≥180/r) F_R(r) = P(180/V \le r) = P(V \ge 180/r) solving for V V flips the inequality, because the transformation is decreasing
With the uniformP(V≥180/r)=20−180/r8 P(V \ge 180/r) = \dfrac{20 – 180/r}{8} in a U(12,20) U(12, 20) , the probability of a piece is its length divided by 8
DifferentiatefR(r)=1808r2=22.5r2 f_R(r) = \dfrac{180}{8r^2} = \dfrac{22.5}{r^2} the derivative of −180/r -180/r is 180/r2 180/r^2
Check∫91522.5r2 dr=22.5(19−115)=22.5⋅245=1 \int_9^{15} \dfrac{22.5}{r^2}\,dr = 22.5\left(\dfrac{1}{9} – \dfrac{1}{15}\right) = 22.5\cdot\dfrac{2}{45} = 1 if it didn’t give 1, something above would be wrong

The same trick gives the probability at the end of the program without integrating anything: P(R>12)=P(180/V>12)=P(V<15)=(15−12)/8=3/8=0.375 P(R > 12) = P(180/V > 12) = P(V < 15) = (15 – 12)/8 = 3/8 = 0.375 . A delivery of more than 12 minutes is the same thing as a bike going under 15 km/h.

The code

set.seed(2026)
n <- 10000
# 1. Kitchen with the inverse of F: F(x) = 1 - exp(-0.1 x)  =>  x = -10 log(1 - u)
u <- runif(n)
kitchen <- -10 * log(1 - u)
round(c(mean = mean(kitchen), sd = sd(kitchen)), 2)    # exp(0.1): 10 and 10
# 2. Bike delivery: V ~ U(12, 20) km/h, 3 km  =>  R = 180 / V minutes
v <- runif(n, 12, 20)
delivery <- 180 / v
round(c(simulated = mean(delivery), theoretical = 22.5 * log(15 / 9),
        naive = 180 / mean(v)), 2)                      # E(R) versus 180 / E(V)
round(c(mean(delivery > 12), 3 / 8), 3)                 # P(R > 12) = P(V < 15)
# The two histograms with their theoretical density on top
par(mfrow = c(1, 2))
hist(kitchen, freq = FALSE, breaks = 40, main = "Kitchen", xlab = "minutes")
curve(dexp(x, 0.1), add = TRUE, col = "red", lwd = 2)
hist(delivery, freq = FALSE, breaks = seq(9, 15, 0.5), main = "Delivery", xlab = "minutes")
curve(22.5 / x^2, from = 9, to = 15, add = TRUE, col = "red", lwd = 2)

Output

mean   sd 
9.96 9.96 
  simulated theoretical       naive 
      11.50       11.49       11.26 
[1] 0.378 0.375
Kitchen made with runif and delivery by bike: histograms with their densityOn the left, the density-scale histogram of 10,000 kitchen times made with minus 10 times the logarithm of 1 minus u, in 2 minute bars up to 60, falling from 0.09 along the red curve of the exponential with rate 0.1. On the right, the histogram of 10,000 deliveries, 180 over the speed, in half-minute bars from 9 to 15, falling from 0.26 to 0.11 along the red curve 22.5 over x squared.0.000.050.100204060minutesdensityKitchendexp(x, 0.1)0.00.10.20.39101112131415minutesDelivery22.5 / x^2
Redrawn with the site colours (the kitchen one, cut at 60 minutes): both transformations are right.

How to read it

  • mean 9.96, sd 9.96: the kitchen times made with runif have mean and standard deviation close to 10, like an exp⁡(0.1) \exp(0.1) , whose mean and standard deviation are both 1/λ=10 1/\lambda = 10 . In the drawing, the histogram on the left goes down following the red dexp curve.
  • simulated 11.50, theoretical 11.49, naive 11.26: the simulated mean delivery matches the theoretical one, 22.5log⁡(15/9)=11.49 22.5\log(15/9) = 11.49 , and not dividing 180 by the mean speed. It is the inequality we saw in the theory: E(180/V)>180/E(V) E(180/V) > 180/E(V) , because 180/v 180/v is convex.
  • 0.378 0.375: the simulated proportion of deliveries over 12 minutes is three thousandths from the theoretical one, that of speeds below 15 km/h, 3/8 3/8 .
  • The histogram on the right isn’t flat even though the speed was: the bars go down from 9 to 15 minutes close to the curve 22.5/r2 22.5/r^2 , which goes from 0.28 to 0.10.

The first five orders, number by number

Before you trust the means of 10,000 orders, look at the first five (u[1:5] and kitchen[1:5], with 4 decimals in the intermediate steps):

Orderu1 - ulog(1 - u)Kitchen (min)Why
10.69870.3013−1.199612.00high u u : small 1−u 1 – u , very negative log, long kitchen time
20.55650.4435−0.81318.13near the middle: kitchen time a bit below the mean of 10
30.14010.8599−0.15101.51small u u : 1−u 1 – u almost 1, log almost 0, very short kitchen time
40.28570.7143−0.33653.36like order 3, but a bit higher
50.55540.4446−0.81058.11almost the same u u as order 2 and almost the same kitchen time: the transformation is increasing

The delivery goes the other way round, because 180/v 180/v is decreasing. The first five values of v are 18.79, 16.77, 18.47, 13.54 and 17.76 km/h, and they give deliveries of 9.58, 10.73, 9.74, 13.29 and 10.14 minutes. The fastest bike (18.79) makes the shortest delivery (9.58), and the only one below 15 km/h, order 4’s, is the only one over 12 minutes. One in five; with 10,000 orders, that proportion settles at the 0.378 in the output.

Check you’ve got it: if runif gave exactly u = 0.5, how long would that kitchen time be? Why isn’t it 10 minutes?

6.93 minutes: −10log⁡(1−0.5)=−10log⁡(0.5)=10log⁡2=6.93 -10\log(1 – 0.5) = -10\log(0.5) = 10\log 2 = 6.93 . It’s the median of the exp⁡(0.1) \exp(0.1) , not its mean. Half the kitchen times are under 6.93 minutes, but the longer ones can be very long (30, 40 minutes) and they pull the mean up to 10: that’s the long tail on the right of the histogram.

Questions you might ask

  • Why -10 * log(1 - u) and not -10 * log(u)? Both work: if U U is uniform, so is 1−U 1 – U . The first is the “textbook” inverse; the second saves a subtraction.
  • Why breaks = seq(9, 15, 0.5) for the delivery? So that the bars start exactly at the support. With breaks = 40, R chooses “round” cut points and some bar may straddle 9 or 15.
  • Is the from = 9, to = 15 in the second curve needed? Yes: without it, curve would draw 22.5/x2 22.5/x^2 along the whole axis of the histogram, also where the density is 0.

Try it yourself

  1. Change the distance to 5 km (delivery <- 300 / v). Work out the new density and its support by hand, and change the curve to check it.
  2. Make a gamma(2, 0.1) by adding two kitchens made with runif (two different u vectors) and compare its histogram with dgamma(x, 2, 0.1).
  3. Replace runif(n, 12, 20) with runif(n, 15, 17) (steadier traffic): do the simulated and the naive means get closer? Why?

Program 2: the joint density of the order with integrate

The idea

The joint density of the kitchen X X and the arrival Y Y is f(x,y)=0.01 e−0.1y f(x, y) = 0.01\,e^{-0.1y} on 0<x<y 0 < x < y . With integrate inside integrate we check that it integrates to 1, get the marginals at a few points and compute a probability, E(XY) E(XY) , the covariance and the correlation. Then, the same with 10,000 simulated orders. First, the error from the anecdote.

Put into words, a double integral in R is two loops, one inside the other. The outer one runs over the kitchen times x x ; for each one, the inner one adds up the density of every possible arrival, and the arrival can only go from x x onwards, because an order can’t arrive before it leaves the kitchen. That’s why the inner limit is x x and not 0: the triangle 0<x<y 0 < x < y is written in the limits. Everything else in the program is that same integral with another function inside or with other limits.

The code

This doesn’t work:

f <- function(x, y) 0.01 * exp(-0.1 * y) * (x < y)    # (x < y) is 1 or 0: the triangle
fx <- function(x) integrate(function(y) f(x, y), x, Inf)$value
integrate(fx, 0, Inf)

Output:

Error in integrate(function(y) f(x, y), x, Inf) : length(lower) == 1 is not TRUE

integrate calls fx with a vector of 21 points at once. Inside fx, that vector ends up as the lower limit of the inner integral, and a limit has to be a single number: hence the message. (If the inner limit were fixed, the error would be another one, evaluation of function gave a result of wrong length, because fx would return one number instead of 21.) Vectorize(fx) turns it into a function that goes through the vector point by point. With that, the whole program:

f <- function(x, y) 0.01 * exp(-0.1 * y) * (x < y)
fX <- Vectorize(function(x) integrate(function(y) f(x, y), x, Inf)$value)  # marginal of X
fY <- Vectorize(function(y) integrate(function(x) f(x, y), 0, y)$value)    # marginal of Y
integrate(fX, 0, Inf)$value                         # the joint density integrates to 1
round(rbind(fX = fX(c(5, 10, 20)), dexp = dexp(c(5, 10, 20), 0.1)), 4)
round(rbind(fY = fY(c(5, 20, 40)), dgamma = dgamma(c(5, 20, 40), 2, 0.1)), 4)
# P(X <= 10, Y <= 30): for each x, y goes from x to 30
pr <- Vectorize(function(x) integrate(function(y) f(x, y), x, 30)$value)
P <- integrate(pr, 0, 10)$value
# Moments with the joint density (double integrals over the triangle)
double_int <- function(g) integrate(Vectorize(function(x)
  integrate(function(y) g(x, y) * f(x, y), x, Inf)$value), 0, Inf)$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
covar <- EXY - EX * EY
round(c(P = P, EX = EX, EY = EY, EXY = EXY, cov = covar, rho = covar / sqrt(VX * VY)), 4)
# The same with 10,000 simulated orders
set.seed(2026)
x <- rexp(10000, 0.1); y <- x + rexp(10000, 0.1)
round(c(P = mean(x <= 10 & y <= 30), EX = mean(x), EY = mean(y), EXY = mean(x * y),
        cov = cov(x, y), rho = cor(x, y)), 4)
plot(x[1:300], y[1:300], pch = 20, xlab = "kitchen (min)", ylab = "arrival (min)")
abline(0, 1, col = "red", lwd = 2)                  # the diagonal y = x

Output

[1] 0.9999997
       [,1]   [,2]   [,3]
fX   0.0607 0.0368 0.0135
dexp 0.0607 0.0368 0.0135
         [,1]   [,2]   [,3]
fY     0.0303 0.0271 0.0073
dgamma 0.0303 0.0271 0.0073
       P       EX       EY      EXY      cov      rho 
  0.5823  10.0000  20.0000 300.0000 100.0000   0.7071 
       P       EX       EY      EXY      cov      rho 
  0.5715  10.2987  20.2225 311.8314 103.5753   0.7163 
The first 300 simulated orders and the diagonalScatter plot of 300 orders: horizontally the kitchen time, from 0 to 65 minutes, and vertically the arrival, from 1 to 75 minutes. All points lie above the red line y equals x; the cloud rises to the right and opens upwards. There are none below the diagonal.020406080010203040506070kitchen (min)arrival (min)y = xno points here
Redrawn with the site colours: the support 0 < x < y, seen with data.

How to read it

  • 0.9999997: practically 1 (the difference is numerical error): the density is well defined on the triangle. Look at the limits: the inner one starts at x, not at 0.
  • The fX and dexp rows are equal: integrating the joint density in y y gives the exponential density of the kitchen, for example 0.0368 at x=10 x = 10 .
  • The fY and dgamma rows too: the arrival is a gamma(2, 0.1). At y=20 y = 20 the density is 0.0271, the highest of the three, because 20 is the mean.
  • P 0.5823: 58 % of the orders leave the kitchen within 10 minutes and arrive within 30. It is 1−e−1−e−3 1 – e^{-1} – e^{-3} , the hand calculation from the theory.
  • EX 10, EY 20, EXY 300, cov 100, rho 0.7071: the theoretical moments, all with double integrals. E(XY)=300 E(XY) = 300 , not 10⋅20=200 10\cdot 20 = 200 : they are not independent.
  • The last numeric row, the simulated one, looks like the theoretical: 0.57, 10.30, 20.22, 311.83, 103.58 and 0.72. E(XY) E(XY) and the covariance are the ones furthest away: they depend on very long orders, which are rare and move the mean a lot.
  • In the drawing, the first 300 orders: none is below the red line y=x y = x . It is the support 0<x<y 0 < x < y seen with data. The cloud goes up to the right (positive correlation) and fans out upwards (the delivery adds more or fewer minutes to each kitchen time).

The 0.5823 and the 300, by hand

The numbers in the output also come out on paper:

QuantityCalculationResultWhy
Inner integral∫x300.01 e−0.1y dy=0.1(e−0.1x−e−3) \int_x^{30} 0.01\,e^{-0.1y}\,dy = 0.1\left(e^{-0.1x} – e^{-3}\right) depends on x x for a fixed kitchen time x x , the arrival goes from x x to 30
Outer integral∫0100.1 e−0.1x dx−0.1⋅10⋅e−3 \int_0^{10} 0.1\,e^{-0.1x}\,dx – 0.1\cdot 10\cdot e^{-3} (1−e−1)−e−3 (1 – e^{-1}) – e^{-3} the first piece is P(X≤10) P(X \le 10) for the exponential; the second, a constant times the length 10
Probability1−0.3679−0.0498 1 – 0.3679 – 0.0498 0.5823the P in the output
E(X2) E(X^2) Var(X)+E(X)2=100+100 \mathrm{Var}(X) + E(X)^2 = 100 + 100 200in an exp⁡(0.1) \exp(0.1) , mean 10 and variance 100
E(XY) E(XY) E(X(X+R))=E(X2)+E(X) E(R)=200+10⋅10 E(X(X + R)) = E(X^2) + E(X)\,E(R) = 200 + 10\cdot 10 300Y=X+R Y = X + R , and X X and R R are independent
Covariance300−10⋅20 300 – 10\cdot 20 100E(XY)−E(X) E(Y) E(XY) – E(X)\,E(Y)
Var(Y) \mathrm{Var}(Y) 100+100 100 + 100 200variances of kitchen and delivery, which add up because they’re independent
Correlation100/100⋅200=1/2 100/\sqrt{100\cdot 200} = 1/\sqrt{2} 0.7071the rho in the output

That’s why the simulation drifts further in E(XY) E(XY) : it has E(X2) E(X^2) inside, and an order with 50 minutes in the kitchen adds 2500 to that sum. A few very long orders push the 300 up to 311.83.

Check you’ve got it: why is the covariance between kitchen time and arrival exactly 100, the variance of the kitchen time?

Because the arrival is the kitchen time plus something that has nothing to do with it. Cov(X,X+R)=Cov(X,X)+Cov(X,R)=Var(X)+0=100 \mathrm{Cov}(X, X + R) = \mathrm{Cov}(X, X) + \mathrm{Cov}(X, R) = \mathrm{Var}(X) + 0 = 100 . All the relationship between X X and Y Y comes from Y Y containing X X ; the delivery only adds noise, and that’s why the correlation isn’t 1 but 0.71.

Questions you might ask

  • Why (x < y) inside f? So that the function is 0 outside the triangle even if you ask it for a point below the diagonal. With the right limits it wouldn’t be needed, but it is a safety net.
  • Why not integrate from 0 to Inf in both variables and let (x < y) do the rest? Because integrate doesn’t cope well with a sudden jump in the function: it can give a wrong value without warning. Using the triangle’s limits is more accurate and faster.
  • Does double_int work for any moment? Yes: you pass it the function g(x,y) g(x, y) and it computes E(g(X,Y)) E(g(X, Y)) on this triangle. For another support, you have to change the inner limits.
What would happen if you integrated over the rectangle and let (x < y) do the rest?

It looks the same: outside the triangle the function is 0, so integrating y y from 0 to Inf should give the same as from x x to Inf. Try it with the marginal of the kitchen time at four points and with P(30<X<100) P(30 < X < 100) :

f <- function(x, y) 0.01 * exp(-0.1 * y) * (x < y)
# Inner integral over the rectangle (y from 0 to Inf) versus the triangle (y from x to Inf)
fX_rect <- Vectorize(function(x) integrate(function(y) f(x, y), 0, Inf)$value)
fX_tri  <- Vectorize(function(x) integrate(function(y) f(x, y), x, Inf)$value)
xs <- c(10, 30, 60, 100)
signif(rbind(rectangle = fX_rect(xs), triangle = fX_tri(xs), dexp = dexp(xs, 0.1)), 3)
# The probability of a kitchen time between 30 and 100 minutes, with each marginal
round(c(rectangle = integrate(fX_rect, 30, 100)$value,
        triangle = integrate(fX_tri, 30, 100)$value,
        theoretical = pexp(100, 0.1) - pexp(30, 0.1)), 4)

Output:

            [,1]    [,2]     [,3]     [,4]
rectangle 0.0368 0.00498 3.21e-07 6.49e-20
triangle  0.0368 0.00498 2.48e-04 4.54e-06
dexp      0.0368 0.00498 2.48e-04 4.54e-06
  rectangle    triangle theoretical 
     0.0468      0.0497      0.0497 

At x=10 x = 10 and x=30 x = 30 the rectangle gets it right, but at x=60 x = 60 it gives almost a thousand times less than it should and at x=100 x = 100 practically 0, with no warning at all. integrate tries a handful of points along the whole y y axis, and when the step starts very far away, almost all of them land in the zero region and miss it. Adding up those errors, the probability comes out as 0.0468 instead of 0.0497, 6 % less. And if you ask for the outer integral up to Inf, it gives up with a maximum number of subdivisions reached. That’s why the limits go on the triangle and the (x < y) is only the safety net.

Try it yourself

  1. Compute the variance of Y−X Y – X with double_int. It must come out 100, the delivery’s, and match Var(X)+Var(Y)−2 Cov(X,Y) \mathrm{Var}(X) + \mathrm{Var}(Y) – 2\,\mathrm{Cov}(X, Y) .
  2. Compute P(Y>2X) P(Y > 2X) (the delivery takes longer than the kitchen) with a double integral and with the simulation. Why must it be 0.5?
  3. Write the conditional f(x∣y) f(x \mid y) in R for y=30 y = 30 and draw it with curve(f(x, 30) / fY(30), 0, 30): it must be a horizontal line at height 1/30 1/30 .

Program 3: dishes and drinks, and the bivariate normal of the delivery

The idea

Two joint distributions that are handled differently:

  1. The table of dishes and drinks (discrete): marginals, checking whether they are independent and the covariance, all with matrix operations.
  2. The bivariate normal of the distance D∼N(3,1) D \sim N(3, 1) km and the delivery time R∼N(15,4) R \sim N(15, 4) min, with ρ=0.8 \rho = 0.8 : checking that a marginal is normal and that the conditional R∣D=5 R \mid D = 5 is N(21.4, 2.4) N(21.4,\ 2.4) , and drawing the joint density with contour lines.

Put into words: in the table there are no integrals. Adding up a row is forgetting about the drinks, and comparing each cell with the product of its marginals is asking “what would we get if they were independent?”. In the bivariate normal, knowing the distance changes two things about the delivery. It moves its mean: 15+0.8⋅41⋅(5−3)=21.4 15 + 0.8\cdot\dfrac{4}{1}\cdot(5 – 3) = 21.4 minutes, because 5 km is two standard deviations above the mean of 3 and the correlation drags the delivery 0.8 of that way. And it narrows it: the standard deviation goes from 4 to 41−0.82=4⋅0.6=2.4 4\sqrt{1 – 0.8^2} = 4\cdot 0.6 = 2.4 , because part of the delivery’s uncertainty was not knowing the distance.

The code

# 1. The joint table of dishes (rows) and drinks (columns)
p <- matrix(c(0.20, 0.15, 0.05,
              0.10, 0.20, 0.10,
              0.02, 0.08, 0.10), nrow = 3, byrow = TRUE,
            dimnames = list(dishes = 1:3, drinks = 0:2))
pX <- rowSums(p); pY <- colSums(p)
round(p - outer(pX, pY), 3)               # joint minus product of marginals
EX <- sum(1:3 * pX); EY <- sum(0:2 * pY)
EXY <- sum(outer(1:3, 0:2) * p)           # sum of x * y * p(x, y)
VX <- sum((1:3)^2 * pX) - EX^2; VY <- sum((0:2)^2 * pY) - EY^2
round(c(EX = EX, EY = EY, EXY = EXY, cov = EXY - EX * EY,
        rho = (EXY - EX * EY) / sqrt(VX * VY)), 3)
# 2. The bivariate normal (D, R): the density written by hand
dbiv <- function(d, r, md = 3, mr = 15, sd = 1, sr = 4, rho = 0.8) {
  q <- ((d - md) / sd)^2 + ((r - mr) / sr)^2 - 2 * rho * (d - md) * (r - mr) / (sd * sr)
  exp(-q / (2 * (1 - rho^2))) / (2 * pi * sd * sr * sqrt(1 - rho^2))
}
fD5 <- integrate(function(r) dbiv(5, r), -Inf, Inf)$value   # marginal of D at d = 5
round(c(fD5, dnorm(5, 3, 1)), 5)
rr <- c(18, 21.4, 25)                                          # conditional R | D = 5
round(rbind(ratio = dbiv(5, rr) / fD5, normal = dnorm(rr, 21.4, 2.4)), 4)
round(c(1 - pnorm(25, 21.4, 2.4), 1 - pnorm(25, 15, 4)), 4)
d <- seq(0, 6, length = 61); r <- seq(3, 27, length = 61)
z <- outer(d, r, dbiv)
contour(d, r, z, xlab = "distance (km)", ylab = "delivery (min)")
abline(v = 5, lty = 2, col = "red")                           # the slice D = 5

Output

      drinks
dishes      0      1     2
     1  0.072 -0.022 -0.05
     2 -0.028  0.028  0.00
     3 -0.044 -0.006  0.05
   EX    EY   EXY   cov   rho 
1.800 0.930 1.890 0.216 0.384 
[1] 0.05399 0.05399
         [,1]   [,2]  [,3]
ratio  0.0609 0.1662 0.054
normal 0.0609 0.1662 0.054
[1] 0.0668 0.0062
Contour lines of the bivariate normal (distance, delivery)Thirteen concentric ellipses, the contour lines from 0.005 to 0.065 that contour draws, centred at distance 3 and delivery 15 and tilted up to the right. A dashed red vertical line at distance 5 crosses the outer ellipses at about 21 minutes.5101520250123456distance (km)delivery (min)0.0050.0200.0350.0500.065abline(v = 5)
Redrawn with the site colours: the ellipses tilt because ρ = 0.8.

How to read it

  • The matrix of differences isn’t all zeros: with 1 dish and 0 drinks, the joint exceeds the product of marginals by 0.072 (0.20 against 0.128). One cell different from 0 is enough to say they are not independent. The positive cells are on the diagonal “few dishes, few drinks” and “many dishes, many drinks”.
  • cov 0.216, rho 0.384: the covariance is positive (more dishes, more drinks), but the correlation is moderate, 0.38. There is a relationship, but there are one-dish orders with two drinks and three-dish orders with none.
  • 0.05399 0.05399: integrating the bivariate normal in r r at the point d=5 d = 5 gives the density of an N(3,1) N(3, 1) at 5. The marginal of a bivariate normal is normal.
  • The ratio and normal rows are equal: the conditional f(5,r)/fD(5) f(5, r)/f_D(5) is exactly the N(21.4, 2.4) N(21.4,\ 2.4) of the formula, at the three points. At 21.4, its mean, it is 0.1662, the maximum.
  • 0.0668 0.0062: a delivery over 25 minutes is ten times more likely if you know the order goes 5 km away (6.68 %) than without knowing the distance (0.62 %).
  • In the drawing, the contour lines from contour are ellipses tilted upwards because ρ=0.8>0 \rho = 0.8 > 0 : more distance, more time. The red line is the slice at D=5 D = 5 ; along it, the ellipses it crosses are centred close to 21 minutes, the conditional mean.

The dishes and drinks table, cell by cell

Matrix operations do all the calculations at once; here they are one by one:

QuantityCalculationResultWhy
Marginal of dishes0.20+0.15+0.05 0.20 + 0.15 + 0.05 ; 0.10+0.20+0.10 0.10 + 0.20 + 0.10 ; 0.02+0.08+0.10 0.02 + 0.08 + 0.10 0.40, 0.40 and 0.20rowSums: add up each row
Marginal of drinks0.20+0.10+0.02 0.20 + 0.10 + 0.02 ; 0.15+0.20+0.08 0.15 + 0.20 + 0.08 ; 0.05+0.10+0.10 0.05 + 0.10 + 0.10 0.32, 0.43 and 0.25colSums: add up each column
Cell (1 dish, 0 drinks)0.20−0.40⋅0.32 0.20 – 0.40\cdot 0.32 0.072the joint minus what independence would give
Cell (2 dishes, 2 drinks)0.10−0.40⋅0.25 0.10 – 0.40\cdot 0.25 0this cell matches, but it’s the only one
E(X) E(X) 1⋅0.40+2⋅0.40+3⋅0.20 1\cdot 0.40 + 2\cdot 0.40 + 3\cdot 0.20 1.80dishes per order
E(Y) E(Y) 0⋅0.32+1⋅0.43+2⋅0.25 0\cdot 0.32 + 1\cdot 0.43 + 2\cdot 0.25 0.93drinks per order
E(XY) E(XY) 0.15+0.10+0.40+0.40+0.24+0.60 0.15 + 0.10 + 0.40 + 0.40 + 0.24 + 0.60 1.89each cell times x⋅y x\cdot y ; the 0-drinks column adds nothing
Covariance1.89−1.80⋅0.93 1.89 – 1.80\cdot 0.93 0.216E(XY)−E(X) E(Y) E(XY) – E(X)\,E(Y)
Variances3.80−1.802=0.56 3.80 – 1.80^2 = 0.56 and 1.43−0.932=0.5651 1.43 – 0.93^2 = 0.5651 E(X2)−E(X)2 E(X^2) – E(X)^2 in each marginal
Correlation0.216/0.56⋅0.5651=0.216/0.5625 0.216/\sqrt{0.56\cdot 0.5651} = 0.216/0.5625 0.384the rho in the output
Check you’ve got it: the cell for 2 dishes and 2 drinks is 0 in p – outer(pX, pY). Why isn’t that enough to say they’re independent?

Because independence asks for the joint to be the product of the marginals in every cell, not in one. That 0.10=0.40⋅0.25 0.10 = 0.40\cdot 0.25 can be a coincidence; one cell that doesn’t match is enough, like the one for 1 dish and 0 drinks (0.20 versus 0.128), for them not to be independent. With nine cells, check all nine.

Questions you might ask

  • Why does outer(1:3, 0:2) * p give ∑xy p(x,y) \sum xy\,p(x, y) ? outer(1:3, 0:2) is the matrix of products x⋅y x\cdot y with the same shape as the table; multiplying cell by cell by p and adding everything up is the expectation.
  • What if the exam asks for mnormt? dmnorm(cbind(d, r), mean = c(3, 15), varcov = matrix(c(1, 3.2, 3.2, 16), 2)) computes the same density as dbiv. The matrix has the variances on the diagonal and ρσDσR=0.8⋅1⋅4=3.2 \rho\sigma_D\sigma_R = 0.8\cdot 1\cdot 4 = 3.2 off it.
  • Why does integrate from -Inf to Inf work here? Because the conditional bell is close to the origin on the scale of the problem (at 21.4 with sd 2.4). With normals very far from the origin, like the filling machine in topic 5, it is better to use finite limits.

Try it yourself

  1. Change rho = 0.8 to rho = 0 in dbiv and repeat the contour: the ellipses are no longer tilted. Check that then dbiv(5, r) equals dnorm(5, 3, 1) * dnorm(r, 15, 4).
  2. With the table, compute the mean number of drinks for 1-dish orders and for 3-dish orders (they are conditional means). Which is larger?
  3. Make up a 3×3 table with the same marginals as the dishes and drinks one but independent: each cell is the product of its marginals.

Typical mistakes in this practice

integrate(fx, 0, Inf) with an fx that does another integral. It gives length(lower) == 1 is not TRUE if the inner limit depends on x, or evaluation of function gave a result of wrong length if it is fixed. Both are fixed with integrate(Vectorize(fx), 0, Inf).

Using in the inner integral the limits of the rectangle that encloses the support (from 0 to Inf) instead of the triangle’s (from x to Inf). Without the (x < y) inside f, the result is wrong; with it, it can still be wrong because integrate doesn’t see the jump well.

Checking the independence of a table by looking at a single cell that matches. You have to look at all of them: p - outer(pX, pY) must be a matrix of zeros.

If an integral takes long or gives a roundoff error warning, try finite limits (the mean plus ten standard deviations is more than enough) before touching anything else.

Try it in the R playground

Open the site’s R playground (or RStudio) and paste this script. It brings the three ideas of the practice together in a short version, with drawings you can change:

set.seed(2026)
# The inverse of F and the change of variable
kitchen <- -10 * log(runif(5000)); delivery <- 180 / runif(5000, 12, 20)
par(mfrow = c(1, 2))
hist(kitchen, freq = FALSE, breaks = 40); curve(dexp(x, 0.1), add = TRUE, col = "red")
hist(delivery, freq = FALSE, breaks = seq(9, 15, 0.5)); curve(22.5 / x^2, 9, 15, add = TRUE, col = "red")
# The joint density of the order: double integral with Vectorize
f <- function(x, y) 0.01 * exp(-0.1 * y) * (x < y)
fX <- Vectorize(function(x) integrate(function(y) f(x, y), x, Inf)$value)
integrate(fX, 0, Inf)
# The bivariate normal and its slice at D = 5
dbiv <- function(d, r, rho = 0.8) {
  q <- (d - 3)^2 + ((r - 15) / 4)^2 - 2 * rho * (d - 3) * (r - 15) / 4
  exp(-q / (2 * (1 - rho^2))) / (2 * pi * 4 * sqrt(1 - rho^2))
}
par(mfrow = c(1, 1))
curve(dbiv(5, x) / dnorm(5, 3, 1), 10, 30, lwd = 2, ylab = "f(r | d = 5)")
curve(dnorm(x, 21.4, 2.4), add = TRUE, col = "red", lty = 2, lwd = 2)

What to look at:

  1. In the two histograms, the bars follow the red curves: the transformations are right.
  2. Remove the Vectorize from fX and run integrate(fX, 0, Inf): it is the error from the anecdote.
  3. In the last drawing, the black curve (the ratio) and the dashed red one (the normal from the formula) overlap. Change rho to 0.5 in both (the conditional mean is 15+0.5⋅4⋅2=19 15 + 0.5\cdot 4\cdot 2 = 19 and the standard deviation, 40.75 4\sqrt{0.75} ) and check that they still match.

Summary

You want…In RIn the order
Simulate with the inverse of F F -10 * log(1 - runif(n)) (or qexp(runif(n), 0.1))mean and sd close to 10
Check a change of variablehist(g(x), freq = FALSE) + curve(f_Y)22.5/r2 22.5/r^2 over the delivery
A double integralintegrate(Vectorize(function(x) integrate(…, x, Inf)$value), 0, Inf)the joint density integrates to 1
A joint momentthe double_int(g) functionE(XY)=300 E(XY) = 300
Marginals of a tablerowSums, colSums0.40 0.40 0.20 and 0.32 0.43 0.25
See whether a table is independentp - outer(pX, pY)not zeros
Covariance and correlation of datacov(x, y), cor(x, y)about 100 and 0.71
Bivariate normal densitythe formula (dbiv) or mnormt::dmnormthe conditional is N(21.4, 2.4) N(21.4,\ 2.4)
Draw a joint densityouter + contour (or persp)tilted ellipses

Checklist: have you practised it?

  • [ ] I can make an exponential with runif and explain why it works.
  • [ ] I can check with a histogram a density obtained by a change of variable.
  • [ ] I can write a double integral in R with the support’s limits and Vectorize.
  • [ ] I can get marginals, E(XY) E(XY) , the covariance and the correlation of a table with rowSums, colSums and outer.
  • [ ] I can check that a conditional of the bivariate normal is the normal from the formula.

With this, on to the exam-style exercises, which mix these programs with hand calculations, as in the EC2.

Next step: exercisesTransformations 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)

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