PS 6.1

9

Consider the previous question.  Verify this result via simulation study using a grid of λ∈{0.5,1,1.5,2} with 10,000 replications per λ.  Plot the simulated densities with the analytic densities superimposed.  Render your solution to Rpubs and submit a link for this question.
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.2     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.1.0     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(patchwork)
set.seed(123)
lambda_grid <- c(0.5, 1, 1.5, 2)
n_sim <- 10000
sim_df <- map_dfr(lambda_grid, function(lam) {
  X <- rexp(n_sim, rate = lam)
  Y <- rexp(n_sim, rate = lam)
  U <- X + Y
  data.frame(U = U, lambda = lam)
})

plots <- map(lambda_grid, function(lam) {
  ggplot(sim_df %>% filter(lambda == lam)) +
    geom_histogram(aes(x = U, y = after_stat(density)),
                   bins = 50,
                   fill = 'lightblue',
                   color = 'black') +
    stat_function(fun = function(u) dgamma(u, shape = 2, rate = lam),
                  color = 'red', size = 1) +
    labs(title = paste0("lambda = ", lam),
         x = "U = X + Y", 
         y = "Density") +
    theme_classic(base_size = 14)
})
Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.
wrap_plots(plots, ncol = 2)