library(purrrfect)
Attaching package: 'purrrfect'
The following objects are masked from 'package:base':
replicate, tabulate
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
N <- 10000
simulate_coin_draw <- \() {
tosses <- sample(c(1, 0), size = 3, replace = TRUE) # 1 = Heads, 0 = Tails
first_h <- match(1, tosses)
y <- case_when(
is.na(first_h) ~ -1,
first_h == 1 ~ 1,
first_h == 2 ~ 2,
first_h == 3 ~ 3
)
return(c(sum(tosses), y))
}
sim_coins <- replicate_int(N, simulate_coin_draw()[1], .as = X) %>%
mutate(
Y = map_int(X, \(x) {
simulate_coin_draw()[2]
})
)
sim_coins_summary <- sim_coins %>%
summarize(cnt = n(), .by = c(X, Y)) %>%
mutate(
joint_prob = cnt / N,
prob_X_given_Y = cnt / sum(cnt), .by = Y
)
sim_coins_table <- sim_coins_summary %>%
pivot_wider(
names_from = Y,
values_from = joint_prob,
names_prefix = 'y=',
id_cols = X,
values_fill = 0
)
print(sim_coins_table)# A tibble: 4 × 5
X `y=2` `y=3` `y=1` `y=-1`
<int> <dbl> <dbl> <dbl> <dbl>
1 1 0.0936 0.0479 0.191 0.0448
2 3 0.0325 0.0154 0.0624 0.018
3 2 0.0912 0.0479 0.183 0.0493
4 0 0.0319 0.0146 0.0591 0.0175