4.3

#12
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── 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
set.seed(450)

beta <- 3
p <- 1 - exp(-1/beta)             
y <- rexp(10000, rate = 1/beta)   
x <- ceiling(y) 

geo_cdf <- tibble(k = 0:max(x),
                  F = pgeom(k - 1, prob = p))

(ggplot()
  + stat_ecdf(data = tibble(x), aes(x = x, col = 'Empirical (simulated)'),
              linewidth = 1)
  + geom_step(data = geo_cdf, aes(x = k, y = F, col = 'Analytic GEO(p)'),
              linewidth = 1, linetype = 'dashed')
  + coord_cartesian(xlim = c(0, 20))
  + labs(x = 'k', y = 'F(k)', col = NULL)
  + theme_classic(base_size = 16)
)

#13

set.seed(450)

lambda <- 0.5
u <- runif(10000)
y <- -log(1 - u) / lambda

sim <- tibble(y)


(ggplot(sim)
  + geom_histogram(aes(x = y, y = after_stat(density)),
                   binwidth = 0.5, boundary = 0,
                   fill = 'grey80', col = 'white')
  + geom_function(fun = \(y) dexp(y, rate = lambda),
                  linewidth = 1, aes(col = 'Analytic EXP(0.5)'))
  + coord_cartesian(xlim = c(0, 15))
  + labs(x = 'y', y = 'f(y)', col = NULL)
  + theme_classic(base_size = 16)
)
Warning in geom_function(fun = function(y) dexp(y, rate = lambda), linewidth = 1, : All aesthetics have length 1, but the data has 10000 rows.
ℹ Please consider using `annotate()` or provide this layer with data containing
  a single row.

(ggplot(sim)
  + stat_ecdf(aes(x = y, col = 'Empirical (simulated)'), linewidth = 1)
  + geom_function(fun = \(y) pexp(y, rate = lambda),
                  linewidth = 1, linetype = 'dashed',
                  aes(col = 'Analytic EXP(0.5)'))
  + coord_cartesian(xlim = c(0, 15))
  + labs(x = 'y', y = 'F(y)', col = NULL)
  + theme_classic(base_size = 16)
)
Warning in geom_function(fun = function(y) pexp(y, rate = lambda), linewidth = 1, : All aesthetics have length 1, but the data has 10000 rows.
ℹ Please consider using `annotate()` or provide this layer with data containing
  a single row.