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.
Table of Contents
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 and the delivery , independent and (10 minutes on average each), and the arrival minute . 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:
- The inverse of : if , . We make kitchen times without using
rexp. - The change of variable: with the speed km/h and a 3 km trip, the delivery has density on .
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 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:
| Step | Calculation | Why |
|---|---|---|
| Support | ; | goes down when goes up: the fastest bike gives the shortest delivery |
| Distribution | solving for flips the inequality, because the transformation is decreasing | |
| With the uniform | in a , the probability of a piece is its length divided by 8 | |
| Differentiate | the derivative of is | |
| Check | 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: . 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
How to read it
mean 9.96, sd 9.96: the kitchen times made withrunifhave mean and standard deviation close to 10, like an , whose mean and standard deviation are both . In the drawing, the histogram on the left goes down following the reddexpcurve.simulated 11.50, theoretical 11.49, naive 11.26: the simulated mean delivery matches the theoretical one, , and not dividing 180 by the mean speed. It is the inequality we saw in the theory: , because 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, .- 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 , 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):
| Order | u | 1 - u | log(1 - u) | Kitchen (min) | Why |
|---|---|---|---|---|---|
| 1 | 0.6987 | 0.3013 | −1.1996 | 12.00 | high : small , very negative log, long kitchen time |
| 2 | 0.5565 | 0.4435 | −0.8131 | 8.13 | near the middle: kitchen time a bit below the mean of 10 |
| 3 | 0.1401 | 0.8599 | −0.1510 | 1.51 | small : almost 1, log almost 0, very short kitchen time |
| 4 | 0.2857 | 0.7143 | −0.3365 | 3.36 | like order 3, but a bit higher |
| 5 | 0.5554 | 0.4446 | −0.8105 | 8.11 | almost the same as order 2 and almost the same kitchen time: the transformation is increasing |
The delivery goes the other way round, because 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: . It’s the median of the , 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 is uniform, so is . 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. Withbreaks = 40, R chooses “round” cut points and some bar may straddle 9 or 15. - Is the
from = 9, to = 15in the secondcurveneeded? Yes: without it,curvewould draw along the whole axis of the histogram, also where the density is 0.
Try it yourself
- Change the distance to 5 km (
delivery <- 300 / v). Work out the new density and its support by hand, and change thecurveto check it. - Make a gamma(2, 0.1) by adding two kitchens made with
runif(two differentuvectors) and compare its histogram withdgamma(x, 2, 0.1). - Replace
runif(n, 12, 20)withrunif(n, 15, 17)(steadier traffic): do thesimulatedand thenaivemeans get closer? Why?
Program 2: the joint density of the order with integrate
The idea
The joint density of the kitchen and the arrival is on . With integrate inside integrate we check that it integrates to 1, get the marginals at a few points and compute a probability, , 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 ; for each one, the inner one adds up the density of every possible arrival, and the arrival can only go from onwards, because an order can’t arrive before it leaves the kitchen. That’s why the inner limit is and not 0: the triangle 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
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 atx, not at 0.- The
fXanddexprows are equal: integrating the joint density in gives the exponential density of the kitchen, for example 0.0368 at . - The
fYanddgammarows too: the arrival is a gamma(2, 0.1). At 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 , the hand calculation from the theory.EX 10, EY 20, EXY 300, cov 100, rho 0.7071: the theoretical moments, all with double integrals. , not : 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. 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 . It is the support 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:
| Quantity | Calculation | Result | Why |
|---|---|---|---|
| Inner integral | depends on | for a fixed kitchen time , the arrival goes from to 30 | |
| Outer integral | the first piece is for the exponential; the second, a constant times the length 10 | ||
| Probability | 0.5823 | the P in the output | |
| 200 | in an , mean 10 and variance 100 | ||
| 300 | , and and are independent | ||
| Covariance | 100 | ||
| 200 | variances of kitchen and delivery, which add up because they’re independent | ||
| Correlation | 0.7071 | the rho in the output |
That’s why the simulation drifts further in : it has 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. . All the relationship between and comes from containing ; the delivery only adds noise, and that’s why the correlation isn’t 1 but 0.71.
Questions you might ask
- Why
(x < y)insidef? 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
Infin both variables and let(x < y)do the rest? Becauseintegratedoesn’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_intwork for any moment? Yes: you pass it the function and it computes 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 from 0 to Inf should give the same as from to Inf. Try it with the marginal of the kitchen time at four points and with :
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 and the rectangle gets it right, but at it gives almost a thousand times less than it should and at practically 0, with no warning at all. integrate tries a handful of points along the whole 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
- Compute the variance of with
double_int. It must come out 100, the delivery’s, and match . - Compute (the delivery takes longer than the kitchen) with a double integral and with the simulation. Why must it be 0.5?
- Write the conditional in R for and draw it with
curve(f(x, 30) / fY(30), 0, 30): it must be a horizontal line at height .
Program 3: dishes and drinks, and the bivariate normal of the delivery
The idea
Two joint distributions that are handled differently:
- The table of dishes and drinks (discrete): marginals, checking whether they are independent and the covariance, all with matrix operations.
- The bivariate normal of the distance km and the delivery time min, with : checking that a marginal is normal and that the conditional is , 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: 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 , 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
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 at the point gives the density of an at 5. The marginal of a bivariate normal is normal.- The
ratioandnormalrows are equal: the conditional is exactly the 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
contourare ellipses tilted upwards because : more distance, more time. The red line is the slice at ; 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:
| Quantity | Calculation | Result | Why |
|---|---|---|---|
| Marginal of dishes | ; ; | 0.40, 0.40 and 0.20 | rowSums: add up each row |
| Marginal of drinks | ; ; | 0.32, 0.43 and 0.25 | colSums: add up each column |
| Cell (1 dish, 0 drinks) | 0.072 | the joint minus what independence would give | |
| Cell (2 dishes, 2 drinks) | 0 | this cell matches, but it’s the only one | |
| 1.80 | dishes per order | ||
| 0.93 | drinks per order | ||
| 1.89 | each cell times ; the 0-drinks column adds nothing | ||
| Covariance | 0.216 | ||
| Variances | and | in each marginal | |
| Correlation | 0.384 | the 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 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) * pgive ?outer(1:3, 0:2)is the matrix of products with the same shape as the table; multiplying cell by cell bypand 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 asdbiv. The matrix has the variances on the diagonal and off it. - Why does
integratefrom-InftoInfwork 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
- Change
rho = 0.8torho = 0indbivand repeat thecontour: the ellipses are no longer tilted. Check that thendbiv(5, r)equalsdnorm(5, 3, 1) * dnorm(r, 15, 4). - 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?
- 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:
- In the two histograms, the bars follow the red curves: the transformations are right.
- Remove the
VectorizefromfXand runintegrate(fX, 0, Inf): it is the error from the anecdote. - In the last drawing, the black curve (the ratio) and the dashed red one (the normal from the formula) overlap. Change
rhoto 0.5 in both (the conditional mean is and the standard deviation, ) and check that they still match.
Summary
| You want… | In R | In the order |
|---|---|---|
| Simulate with the inverse of | -10 * log(1 - runif(n)) (or qexp(runif(n), 0.1)) | mean and sd close to 10 |
| Check a change of variable | hist(g(x), freq = FALSE) + curve(f_Y) | over the delivery |
| A double integral | integrate(Vectorize(function(x) integrate(…, x, Inf)$value), 0, Inf) | the joint density integrates to 1 |
| A joint moment | the double_int(g) function | |
| Marginals of a table | rowSums, colSums | 0.40 0.40 0.20 and 0.32 0.43 0.25 |
| See whether a table is independent | p - outer(pX, pY) | not zeros |
| Covariance and correlation of data | cov(x, y), cor(x, y) | about 100 and 0.71 |
| Bivariate normal density | the formula (dbiv) or mnormt::dmnorm | the conditional is |
| Draw a joint density | outer + contour (or persp) | tilted ellipses |
Checklist: have you practised it?
- [ ] I can make an exponential with
runifand 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, , the covariance and the correlation of a table with
rowSums,colSumsandouter. - [ ] 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 →



