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   4.0.0     ✔ 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(purrrfect)

Attaching package: 'purrrfect'

The following objects are masked from 'package:base':

    replicate, tabulate
library(patchwork)

N <- 10000
(simstudy <- parameters(~lambda,
                        c(0.5, 1, 1.5, 2)
                        )
  %>% add_trials(N)
  %>% mutate(X = map_dbl(lambda, \(l) rexp(1, rate = l)))
  %>% mutate(Y = map_dbl(lambda, \(l) rexp(1, rate = l)))
  %>% mutate(U = X + Y)
)
# A tibble: 40,000 × 5
   lambda .trial     X     Y     U
    <dbl>  <dbl> <dbl> <dbl> <dbl>
 1    0.5      1 0.625 2.88   3.50
 2    0.5      2 0.422 1.44   1.86
 3    0.5      3 2.83  0.463  3.30
 4    0.5      4 1.59  3.20   4.79
 5    0.5      5 8.75  0.129  8.88
 6    0.5      6 0.608 2.83   3.44
 7    0.5      7 2.12  0.416  2.53
 8    0.5      8 4.97  0.857  5.83
 9    0.5      9 1.18  3.57   4.76
10    0.5     10 1.30  3.13   4.43
# ℹ 39,990 more rows
(ggplot(data = simstudy)
  + geom_point(aes(x = X, y = Y), alpha = 0.5)
  + theme_classic()
) + 

(ggplot(data = simstudy)
 + geom_histogram(aes(x = U, y = after_stat(density)),
                fill = 'cornflowerblue',
                color = 'black',
                center = 0.02,
                binwidth = 0.04)
 + stat_function(fun = function(u) dgamma(u, shape = 2, rate = lambda),
                 linewidth = 1)
 +facet_grid(~lambda, labeller = label_both, scales = 'free_x')
 +theme_classic()
)
Warning: Computation failed in `stat_function()`.
Computation failed in `stat_function()`.
Computation failed in `stat_function()`.
Computation failed in `stat_function()`.
Caused by error in `fun()`:
! object 'lambda' not found