sim5.7-8

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
library(purrrfect)

Attaching package: 'purrrfect'

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

    replicate, tabulate
sim_fires <- replicate(10000, {
  counts <- as.vector(rmultinom(1, size = 50, prob = c(0.73, 0.20, 0.07)))
  c(Y1 = counts[1], Y2 = counts[2], Y3 = counts[3])
}) |>
  unnest_wider(-.trial)

ggplot(sim_fires, aes(x = Y1, y = Y2)) +
  geom_bin2d(binwidth = c(1, 1)) +
  scale_fill_viridis_c(name = "Count") +
  labs(
    title = "Joint Distribution of Family Home (Y1) and Apartment (Y2) Fires",
    subtitle = "10,000 simulations of n = 50 residential fires",
    x = "Number of Family Home Fires (Y1)",
    y = "Number of Apartment Fires (Y2)"
  ) +
  theme_bw()

# 3a. Most common (Y1, Y2) combination
sim_fires |>
  count(Y1, Y2, sort = TRUE) |>
  head(5)
# A tibble: 5 × 3
     Y1    Y2     n
  <int> <int> <int>
1    37    10   322
2    38     9   295
3    36    11   285
4    39     9   280
5    36    10   273
# 3b. Cov(Y1, Y2)
sim_fires |>
  summarize(
    Simulated_Cov = cov(Y1, Y2),
    Analytic_Cov  = -50 * 0.73 * 0.20,
    Difference    = Simulated_Cov - Analytic_Cov
  )
# A tibble: 1 × 3
  Simulated_Cov Analytic_Cov Difference
          <dbl>        <dbl>      <dbl>
1         -7.13         -7.3      0.173
library(tidyverse)
library(purrrfect)

bvnorm_sim <- parameters(
  ~sigx,      ~sigy,      ~rho,
  c(0.5, 1),  c(0.5, 1),  c(-0.8, -0.4, 0, 0.4, 0.8)
) |>
  add_trials(10000) |>
  mutate(
    z1 = rnorm(n()),
    z2 = rnorm(n()),
    x  = 5 + sigx * z1,
    y  = 5 + sigy * (rho * z1 + sqrt(1 - rho^2) * z2)
  )

ggplot(data = bvnorm_sim) +
  geom_point(aes(x = x, y = y), alpha = 0.5, size = 0.5) +
  geom_point(aes(x = 5, y = 5), col = "red") +
  facet_grid(rho ~ sigx + sigy, labeller = label_both) +
  theme_bw()
Warning in geom_point(aes(x = 5, y = 5), col = "red"): All aesthetics have length 1, but the data has 200000 rows.
ℹ Please consider using `annotate()` or provide this layer with data containing
  a single row.

# 1. Simulate 10,000 (X, Y) realizations using purrrfect::replicate()
sim_xy <- replicate(10000, {
  x <- rexp(1, rate = 1)
  y <- x + rexp(1, rate = 1)
  c(x = x, y = y)
}) |>
  unnest_wider(-.trial)

# 2. Scatterplot with analytic and simulated conditional mean functions
ggplot(sim_xy, aes(x = x, y = y)) +
  geom_point(alpha = 0.15, size = 0.8) +
  geom_smooth(
    aes(color = "Simulated E(Y|X)"),
    method = "lm",
    se = FALSE,
    linewidth = 1
  ) +
  geom_abline(
    aes(intercept = 1, slope = 1, color = "Analytic E(Y|X) = 1 + X"),
    linetype = "dashed",
    linewidth = 1
  ) +
  scale_color_manual(
    name = "Conditional Mean",
    values = c("Simulated E(Y|X)" = "blue", "Analytic E(Y|X) = 1 + X" = "red")
  ) +
  labs(
    title = "Simulated Joint Distribution of (X, Y) with Conditional Mean E(Y|X)",
    subtitle = "10,000 realizations from f(x, y) = exp(-y), 0 <= x < y",
    x = "X",
    y = "Y"
  ) +
  theme_bw()
`geom_smooth()` using formula = 'y ~ x'

# 3. Approximate parts e) through j) from the simulated data
sim_xy |>
  summarize(
    # e) P(X <= 1, Y <= 2) and P(X <= 1, Y <= 0.5)
    e1_P_X1_Y2   = mean(x <= 1 & y <= 2),
    e2_P_X1_Y0.5 = mean(x <= 1 & y <= 0.5),
    
    # f) P(Y <= 2 | X <= 1)
    f_P_Y2_given_X1 = mean(y[x <= 1] <= 2),
    
    # g) P(Y < X^2)
    g_P_Y_less_X2 = mean(y < x^2),
    
    # h) E(Y) and E(X)
    h_mu_Y = mean(y),
    h_mu_X = mean(x),
    
    # i) Cov(X, Y) and Cor(X, Y)
    i_Cov_XY = cov(x, y),
    i_Cor_XY = cor(x, y),
    
    # j) E(Y - X) and Var(Y - X)
    j_E_Y_minus_X   = mean(y - x),
    j_Var_Y_minus_X = var(y - x)
  ) |>
  pivot_longer(everything(), names_to = "Quantity", values_to = "Simulated_Estimate")
# A tibble: 10 × 2
   Quantity        Simulated_Estimate
   <chr>                        <dbl>
 1 e1_P_X1_Y2                  0.498 
 2 e2_P_X1_Y0.5                0.0897
 3 f_P_Y2_given_X1             0.789 
 4 g_P_Y_less_X2               0.226 
 5 h_mu_Y                      2.00  
 6 h_mu_X                      0.997 
 7 i_Cov_XY                    0.995 
 8 i_Cor_XY                    0.707 
 9 j_E_Y_minus_X               1.01  
10 j_Var_Y_minus_X             1.01  
# 4. Part k): Use lm() to estimate regression coefficients
fit_lm <- lm(y ~ x, data = sim_xy)
summary(fit_lm)

Call:
lm(formula = y ~ x, data = sim_xy)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.0386 -0.7150 -0.3116  0.3763  8.3043 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  0.99424    0.01425   69.78   <2e-16 ***
x            1.01187    0.01013   99.86   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.005 on 9998 degrees of freedom
Multiple R-squared:  0.4993,    Adjusted R-squared:  0.4993 
F-statistic:  9972 on 1 and 9998 DF,  p-value: < 2.2e-16
coef(fit_lm)
(Intercept)           x 
  0.9942357   1.0118738