-
Notifications
You must be signed in to change notification settings - Fork 18
/
07-simulation1.Rmd
847 lines (657 loc) · 25.9 KB
/
07-simulation1.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# Simulation 1
## Load packages and set plotting theme
```{r, message=FALSE}
library("knitr")
library("kableExtra")
library("MASS")
library("patchwork")
library("tidyverse")
```
```{r}
theme_set(theme_classic() + #set the theme
theme(text = element_text(size = 20))) #set the default text size
opts_chunk$set(comment = "",
fig.show = "hold")
```
## Sampling
### Drawing numbers from a vector
```{r}
numbers = 1:3
numbers %>%
sample(size = 10,
replace = T)
```
Use the `prob = ` argument to change the probability with which each number should be drawn.
```{r}
numbers = 1:3
numbers %>%
sample(size = 10,
replace = T,
prob = c(0.8, 0.1, 0.1))
```
Make sure to set the seed in order to make your code reproducible. The code chunk below may give a different outcome each time is run.
```{r no-seed}
numbers = 1:5
numbers %>%
sample(5)
```
The chunk below will produce the same outcome every time it's run.
```{r with-seed}
set.seed(1)
numbers = 1:5
numbers %>%
sample(5)
```
### Drawing rows from a data frame
Generate a data frame.
```{r}
set.seed(1)
n = 10
df.data = tibble(trial = 1:n,
stimulus = sample(x = c("flower", "pet"),
size = n,
replace = T),
rating = sample(x = 1:10,
size = n,
replace = T))
```
Sample a given number of rows.
```{r}
set.seed(1)
df.data %>%
slice_sample(n = 6,
replace = T)
```
```{r}
set.seed(1)
df.data %>%
slice_sample(prop = 0.5)
```
Note that there is a whole family of `slice()` functions in dplyr. Take a look at the help file here:
```{r, eval=FALSE}
help(slice)
```
## Working with distributions
Every distribution that R handles has four functions. There is a root name, for example, the root name for the normal distribution is `norm`. This root is prefixed by one of the letters here:
```{r, echo=F}
tibble(letter = c("`d`","`p`","`q`","`r`"),
description = c('for "__density__", the density function (probability function (for _discrete_ variables) or probability density function (for _continuous_ variables))',
'for "__probability__", the cumulative distribution function',
'for "__quantile__", the inverse cumulative distribution function',
'for "__random__", a random variable having the specified distribution'),
example = c("`dnorm()`", "`pnorm()`", "`qnorm()`", "`rnorm()`")) %>%
kable() %>%
kable_styling(bootstrap_options = "striped",
full_width = F)
```
For the normal distribution, these functions are `dnorm`, `pnorm`, `qnorm`, and `rnorm`. For the binomial distribution, these functions are `dbinom`, `pbinom`, `qbinom`, and `rbinom`. And so forth.
You can get more info about the distributions that come with R via running `help(Distributions)` in your console. If you need a distribution that doesn't already come with R, then take a look [here](https://cran.r-project.org/web/views/Distributions.html) for many more distributions that can be loaded with different R packages.
### Plotting distributions
Here's an easy way to plot distributions in `ggplot2` using the `stat_function()` function. We take a look at a normal distribution of height (in cm) with `mean = 180` and `sd = 10` (as this is the example we run with in class).
```{r, results = "hold"}
ggplot(data = tibble(height = c(150, 210)),
mapping = aes(x = height)) +
stat_function(fun = ~ dnorm(x = .,
mean = 180,
sd = 10))
```
Note that the data frame I created with `tibble()` only needs to have the minimum and the maximum value of the x-range that we are interested in. Here, I chose `150` and `210` as the minimum and maximum, respectively (which is the mean +/- 3 standard deviations).
The `stat_function()` is very flexible. We can define our own functions and plot these like here:
```{r, results='hold'}
# define the breakpoint function
fun.breakpoint = function(x, breakpoint){
x[x < breakpoint] = breakpoint
return(x)
}
# plot the function
ggplot(data = tibble(x = c(-5, 5)),
mapping = aes(x = x)) +
stat_function(fun = ~ fun.breakpoint(x = .,
breakpoint = 2))
```
Here, I defined a breakpoint function. If the value of `x` is below the breakpoint, `y` equals the value of the breakpoint. If the value of `x` is greater than the breakpoint, then `y` equals `x`.
### Sampling from distributions
For each distribution, R provides a way of sampling random number from this distribution. For the normal distribution, we can use the `rnorm()` function to take random samples.
So let's take some random samples and plot a histogram.
```{r}
# make this example reproducible
set.seed(1)
# define how many samples to draw
tmp.nsamples = 100
# make a data frame with the samples
df.plot = tibble(height = rnorm(n = tmp.nsamples,
mean = 180,
sd = 10))
# plot the samples using a histogram
ggplot(data = df.plot,
mapping = aes(x = height)) +
geom_histogram(binwidth = 1,
color = "black",
fill = "lightblue") +
scale_x_continuous(breaks = c(160, 180, 200)) +
coord_cartesian(xlim = c(150, 210),
expand = F)
# remove all variables with tmp in their name
rm(list = ls() %>%
str_subset(pattern = "tmp."))
```
Let's see how many samples it takes to closely approximate the shape of the normal distribution with our histogram of samples.
```{r}
# make this example reproducible
set.seed(1)
# play around with this value
# tmp.nsamples = 100
tmp.nsamples = 10000
tmp.binwidth = 1
# make a data frame with the samples
df.plot = tibble(height = rnorm(n = tmp.nsamples,
mean = 180,
sd = 10))
# adjust the density of the normal distribution based on the samples and binwidth
fun.dnorm = function(x, mean, sd, n, binwidth){
dnorm(x = x, mean = mean, sd = sd) * n * binwidth
}
# plot the samples using a histogram
ggplot(data = df.plot,
mapping = aes(x = height)) +
geom_histogram(binwidth = tmp.binwidth,
color = "black",
fill = "lightblue") +
stat_function(fun = ~ fun.dnorm(x = .,
mean = 180,
sd = 10,
n = tmp.nsamples,
binwidth = tmp.binwidth),
xlim = c(min(df.plot$height), max(df.plot$height)),
linewidth = 2) +
annotate(geom = "text",
label = str_c("n = ", tmp.nsamples),
x = -Inf,
y = Inf,
hjust = -0.1,
vjust = 1.1,
size = 10,
family = "Courier New") +
scale_x_continuous(breaks = c(160, 180, 200)) +
coord_cartesian(xlim = c(150, 210),
expand = F)
# remove all variables with tmp in their name
rm(list = ls() %>%
str_subset(pattern = "tmp."))
```
With 10,000 samples, our histogram of samples already closely resembles the theoretical shape of the normal distribution.
To keep my environment clean, I've named the parameters `tmp.nsamples` and `tmp.binwidth` and then, at the end of the code chunk, I removed all variables from the environment that have "tmp." in their name using the `ls()` function (which prints out all variables in the environment as a vector), and the `str_subset()` function which filters out only those variables that contain the specified pattern.
### Understanding `density()`
First, let's calculate the density for a set of observations and store them in a data frame.
```{r, fig.cap='Density estimation.'}
# calculate density
observations = c(1, 1.2, 1.5, 2, 3)
bandwidth = 0.25 # bandwidth (= sd) of the Gaussian distribution
tmp.density = density(observations,
kernel = "gaussian",
bw = bandwidth,
n = 512)
# save density as data frame
df.density = tibble(x = tmp.density$x,
y = tmp.density$y)
df.density %>%
head() %>%
kable(digits = 3) %>%
kable_styling(bootstrap_options = "striped",
full_width = F)
```
Now, let's plot the density.
```{r}
ggplot(data = df.density,
mapping = aes(x = x, y = y)) +
geom_line(size = 2) +
geom_point(data = enframe(observations),
mapping = aes(x = value, y = 0),
size = 3)
```
This density shows the sum of the densities of normal distributions that are centered at the observations with the specified bandwidth.
```{r}
# add densities for the individual normal distributions
for (i in 1:length(observations)){
df.density[[str_c("observation_",i)]] = dnorm(df.density$x,
mean = observations[i],
sd = bandwidth)
}
# sum densities
df.density = df.density %>%
mutate(sum_norm = rowSums(select(., contains("observation_"))),
y = y * length(observations))
df.density %>%
head() %>%
kable(digits = 3) %>%
kable_styling(bootstrap_options = "striped",
full_width = F)
```
Now, let's plot the individual densities as well as the overall density.
```{r}
# colors of individual Gaussian distributions
colors = c("blue", "green", "red", "purple", "orange")
bandwidth = 0.25
# original density
p = ggplot(data = df.density, aes(x = x,
y = y)) +
geom_line(linewidth = 2)
# individual densities
for (i in 1:length(observations)){
p = p + stat_function(fun = dnorm,
args = list(mean = observations[i], sd = bandwidth),
color = colors[i])
}
# individual observations
p = p + geom_point(data = enframe(observations),
mapping = aes(x = value, y = 0, color = factor(1:5)),
size = 3,
show.legend = F) +
scale_color_manual(values = colors)
# sum of the individual densities
p = p +
geom_line(data = df.density,
aes(x = x, y = sum_norm),
size = 1,
color = "red",
linetype = 2)
p # print the figure
```
Here are the same results when specifying a different bandwidth:
```{r}
# colors of individual Gaussian distributions
colors = c("blue", "green", "red", "purple", "orange")
# calculate density
observations = c(1, 1.2, 1.5, 2, 3)
bandwidth = 0.5 # bandwidth (= sd) of the Gaussian distribution
tmp.density = density(observations,
kernel = "gaussian",
bw = bandwidth,
n = 512)
# save density as data frame
df.density = tibble(
x = tmp.density$x,
y = tmp.density$y
)
# add densities for the individual normal distributions
for (i in 1:length(observations)){
df.density[[str_c("observation_",i)]] = dnorm(df.density$x,
mean = observations[i],
sd = bandwidth)
}
# sum densities
df.density = df.density %>%
mutate(sum_norm = rowSums(select(., contains("observation_"))),
y = y * length(observations))
# original plot
p = ggplot(data = df.density, aes(x = x, y = y)) +
geom_line(linewidth = 2) +
geom_point(data = enframe(observations),
mapping = aes(x = value,
y = 0,
color = factor(1:5)),
size = 3,
show.legend = F) +
scale_color_manual(values = colors)
# add individual Gaussians
for (i in 1:length(observations)){
p = p + stat_function(fun = dnorm,
args = list(mean = observations[i], sd = bandwidth),
color = colors[i])
}
# add the sum of Gaussians
p = p +
geom_line(data = df.density,
aes(x = x, y = sum_norm),
size = 1,
color = "red",
linetype = 2)
p
```
### Cumulative probability distribution
```{r}
ggplot(data = tibble(height = c(150, 210)),
mapping = aes(x = height)) +
stat_function(fun = ~ pnorm(q = .,
mean = 180,
sd = 10)) +
scale_x_continuous(breaks = c(160, 180, 200)) +
coord_cartesian(xlim = c(150, 210),
ylim = c(0, 1.05),
expand = F) +
labs(x = "height",
y = "cumulative probability")
```
Let's find the cumulative probability of a particular value.
```{r}
tmp.x = 190
tmp.y = pnorm(tmp.x, mean = 180, sd = 10)
print(tmp.y %>% round(3))
# draw the cumulative probability distribution and show the value
ggplot(data = tibble(height = c(150, 210)),
mapping = aes(x = height)) +
stat_function(fun = ~ pnorm(q = .,
mean = 180,
sd = 10 )) +
annotate(geom = "point",
x = tmp.x,
y = tmp.y,
size = 4,
color = "blue") +
geom_segment(mapping = aes(x = tmp.x,
xend = tmp.x,
y = 0,
yend = tmp.y),
size = 1,
color = "blue") +
geom_segment(mapping = aes(x = -5,
xend = tmp.x,
y = tmp.y,
yend = tmp.y),
size = 1,
color = "blue") +
scale_x_continuous(breaks = c(160, 180, 200)) +
coord_cartesian(xlim = c(150, 210),
ylim = c(0, 1.05),
expand = F) +
labs(x = "height",
y = "cumulative probability")
# remove all variables with tmp in their name
rm(list = str_subset(string = ls(), pattern = "tmp."))
```
Let's illustrate what this would look like using a normal density plot.
```{r}
ggplot(data = tibble(height = c(150, 210)),
mapping = aes(x = height)) +
stat_function(fun = ~ dnorm(., mean = 180, sd = 10),
geom = "area",
fill = "lightblue",
xlim = c(150, 190)) +
stat_function(fun = ~ dnorm(., mean = 180, sd = 10),
linewidth = 1.5) +
scale_x_continuous(breaks = c(160, 180, 200)) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1))) +
coord_cartesian(xlim = c(150, 210)) +
labs(x = "height", y = "density")
```
### Inverse cumulative distribution
```{r}
ggplot(data = tibble(probability = c(0, 1)),
mapping = aes(x = probability)) +
stat_function(fun = ~ qnorm(p = .,
mean = 180,
sd = 10)) +
scale_x_continuous(breaks = seq(from = 0, to = 1, by = 0.1)) +
scale_y_continuous(limits = c(160, 200)) +
coord_cartesian(xlim = c(0, 1.05),
expand = F) +
labs(y = "height",
x = "cumulative probability")
```
And let's compute the inverse cumulative probability for a particular value.
```{r}
tmp.x = 0.3
tmp.y = qnorm(tmp.x, mean = 180, sd = 10)
tmp.y %>%
round(3) %>%
print()
# draw the cumulative probability distribution and show the value
ggplot(data = tibble(probability = c(0, 1)),
mapping = aes(x = probability)) +
stat_function(fun = ~ qnorm(., mean = 180, sd = 10)) +
annotate(geom = "point",
x = tmp.x,
y = tmp.y,
size = 4,
color = "blue") +
geom_segment(mapping = aes(x = tmp.x,
xend = tmp.x,
y = 160,
yend = tmp.y),
size = 1,
color = "blue") +
geom_segment(mapping = aes(x = 0,
xend = tmp.x,
y = tmp.y,
yend = tmp.y),
size = 1,
color = "blue") +
scale_x_continuous(breaks = seq(from = 0, to = 1, by = 0.1)) +
scale_y_continuous(limits = c(160, 200)) +
coord_cartesian(xlim = c(0, 1.05),
expand = F) +
labs(x = "cumulative probability",
y = "height")
# remove all variables with tmp in their name
rm(list = str_subset(string = ls(), pattern = "tmp."))
```
### Computing probabilities
#### Via probability distributions
Let's compute the probability of observing a particular value $x$ in a given range.
```{r}
tmp.lower = 170
tmp.upper = 180
tmp.prob = pnorm(tmp.upper, mean = 180, sd = 10) -
pnorm(tmp.lower, mean = 180, sd = 10)
tmp.prob
ggplot(data = tibble(x = c(150, 210)),
mapping = aes(x = x)) +
stat_function(fun = ~ dnorm(., mean = 180, sd = 10),
geom = "area",
fill = "lightblue",
xlim = c(tmp.lower, tmp.upper),
color = "black",
linetype = 2) +
stat_function(fun = ~ dnorm(., mean = 180, sd = 10),
linewidth = 1.5) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1))) +
scale_x_continuous(breaks = c(160, 180, 200)) +
coord_cartesian(xlim = c(150, 210)) +
labs(x = "height",
y = "density")
# remove all variables with tmp in their name
rm(list = str_subset(string = ls(), pattern = "tmp."))
```
We find that ~34% of the heights are between 170 and 180 cm.
#### Via sampling
We can also compute the probability of observing certain events using sampling. We first generate samples from the desired probability distribution, and then use these samples to compute our statistic of interest.
```{r}
# let's compute the probability of observing a value within a certain range
tmp.lower = 170
tmp.upper = 180
# make example reproducible
set.seed(1)
# generate some samples and store them in a data frame
tmp.nsamples = 10000
df.samples = tibble(height = rnorm(n = tmp.nsamples, mean = 180, sd = 10))
# compute the probability that sample lies within the range of interest
tmp.prob = df.samples %>%
filter(height >= tmp.lower,
height <= tmp.upper) %>%
summarize(prob = n()/tmp.nsamples)
# illustrate the result using a histogram
ggplot(data = df.samples,
mapping = aes(x = height)) +
geom_histogram(binwidth = 1,
color = "black",
fill = "lightblue") +
geom_vline(xintercept = tmp.lower,
size = 1,
color = "red",
linetype = 2) +
geom_vline(xintercept = tmp.upper,
size = 1,
color = "red",
linetype = 2) +
annotate(geom = "label",
label = str_c(tmp.prob %>% round(3) * 100, "%"),
x = 175,
y = 200,
hjust = 0.5,
size = 10) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1))) +
labs(x = "height")
# remove all variables with tmp in their name
rm(list = str_subset(string = ls(), pattern = "tmp."))
```
## Pinguin exercise
Assume that we have a population of penguins whose height is distribution according to a Gamma distribution with a `shape` parameter of 50, and `rate` parameter of 1.
### Make the plot
```{r}
ggplot(data = tibble(height = c(30, 70)),
mapping = aes(x = height)) +
stat_function(fun = ~ dgamma(.,
shape = 50,
rate = 1))
```
### Analytic solutions
#### Question: A 60cm tall Penguin claims that no more than 10% are taller than her. Is she correct?
```{r}
1 - pgamma(60, shape = 50, rate = 1)
```
Answer: Yes, she is correct. Only ~ 8.4% of Penguins are taller than her.
#### Question: Are there more penguins between 50 and 55cm or between 55 and 65cm?
```{r}
first_range = pgamma(55, shape = 50, rate = 1) - pgamma(50, shape = 50, rate = 1)
second_range = pgamma(65, shape = 50, rate = 1) - pgamma(55, shape = 50, rate = 1)
first_range - second_range
```
Answer: There are 4% more Penguins between 50 and 55cm than between 55 and 65 cm.
#### Question: What size is a Penguin who is taller than 75% of the rest?
```{r}
qgamma(0.75, shape = 50, rate = 1)
```
Answer: A Penguin who is ~54.6cm tall is taller than 75% of the rest.
### Sampling solution
Let's just simulate a bunch of Penguins, yay!
```{r}
set.seed(1)
df.penguins = tibble(height = rgamma(n = 100000, shape = 50, rate = 1))
```
#### Question: A 60cm tall Penguin claims that no more than 10% are taller than her. Is she correct?
```{r}
df.penguins %>%
summarize(probability = sum(height > 60) / n())
```
Answer: Yes, she is correct. Only ~ 8.3% of Penguins are taller than her.
#### Question: Are there more penguins between 50 and 55cm or between 55 and 65cm?
```{r}
df.penguins %>%
summarize(probability = (sum(between(height, 50, 55)) - sum(between(height, 55, 65)))/n())
```
Answer: There are 3.9% more Penguins between 50 and 55cm than between 55 and 65 cm.
#### Question: What size is a Penguin who is taller than 75% of the rest?
```{r}
df.penguins %>%
arrange(height) %>%
slice_head(prop = 0.75) %>%
summarize(height = max(height))
```
Answer: A Penguin who is ~54.6cm tall is taller than 75% of the rest.
## Bayesian inference with the normal distribution
Let's consider the following scenario. You are helping out at a summer camp. This summer, two different groups of kids go to the same summer camp. The chess kids, and the basketball kids. The chess summer camp is not quite as popular as the basketball summer camp (shocking, I know!). In fact, twice as many children have signed up for the basketball camp.
When signing up for the camp, the children were asked for some demographic information including their height in cm. Unsurprisingly, the basketball players tend to be taller on average than the chess players. In fact, the basketball players' height is approximately normally distributed with a mean of 180cm and a standard deviation of 10cm. For the chess players, the mean height is 170cm with a standard deviation of 8cm.
At the camp site, a child walks over to you and asks you where their gym is. You gage that the child is around 175cm tall. Where should you direct the child to? To the basketball gym, or to the chess gym?
### Analytic solution
```{r}
height = 175
# priors
prior_basketball = 2/3
prior_chess = 1/3
# likelihood
mean_basketball = 180
sd_basketball = 10
mean_chess = 170
sd_chess = 8
likelihood_basketball = dnorm(height, mean = mean_basketball, sd = sd_basketball)
likelihood_chess = dnorm(height, mean = mean_chess, sd = sd_chess)
# posterior
posterior_basketball = (likelihood_basketball * prior_basketball) /
((likelihood_basketball * prior_basketball) + (likelihood_chess * prior_chess))
print(posterior_basketball)
```
### Solution via sampling
Let's do the same thing via sampling.
```{r}
# number of kids
tmp.nkids = 10000
# make reproducible
set.seed(1)
# priors
prior_basketball = 2/3
prior_chess = 1/3
# likelihood functions
mean_basketball = 180
sd_basketball = 10
mean_chess = 170
sd_chess = 8
# data frame with the kids
df.camp = tibble(kid = 1:tmp.nkids,
sport = sample(c("chess", "basketball"),
size = tmp.nkids,
replace = T,
prob = c(prior_chess, prior_basketball))) %>%
rowwise() %>%
mutate(height = ifelse(test = sport == "chess",
yes = rnorm(n = .,
mean = mean_chess,
sd = sd_chess),
no = rnorm(n = .,
mean = mean_basketball,
sd = sd_basketball))) %>%
ungroup
print(df.camp)
```
Now we have a data frame with kids whose height was randomly sampled depending on which sport they do. I've used the `sample()` function to assign a sport to each kid first using the `prob = ` argument to make sure that a kid is more likely to be assigned the sport "basketball" than "chess".
Note that the solution above is not particularly efficient since it uses the `rowwise()` function to make sure that a different random value for height is drawn for each row. Running this code will get slow for large samples. A more efficient solution would be the following:
```{r}
# number of kids
tmp.nkids = 100000
# make reproducible
set.seed(3)
df.camp2 = tibble(
kid = 1:tmp.nkids,
sport = sample(c("chess", "basketball"),
size = tmp.nkids,
replace = T,
prob = c(prior_chess, prior_basketball))) %>%
arrange(sport) %>%
mutate(height = c(rnorm(sum(sport == "basketball"),
mean = mean_basketball,
sd = sd_basketball),
rnorm(sum(sport == "chess"),
mean = mean_chess,
sd = sd_chess)))
```
In this solution, I take advantage of the fact that `rnorm()` is vectorized. That is, it can produce many random draws in one call. To make this work, I first arrange the data frame, and then draw the correct number of samples from each of the two distributions. This works fast, even if I'm drawing a large number of samples.
How can we now use these samples to answer our question of interest? Let's see what doesn't work first:
```{r, eval=F}
tmp.height = 175
df.camp %>%
filter(height == tmp.height) %>%
count(sport) %>%
pivot_wider(names_from = sport, values_from = n) %>%
summarize(prob_basketball = basketball/(basketball + chess))
```
The reason this doesn't work is because none of our kids is exactly 175cm tall. Instead, we need to filter kids that are within a certain height range.
```{r}
tmp.height = 175
tmp.margin = 1
df.camp %>%
filter(between(height,
left = tmp.height - tmp.margin,
right = tmp.height + tmp.margin)) %>%
count(sport) %>%
pivot_wider(names_from = sport,
values_from = n) %>%
summarize(prob_basketball = basketball/(basketball + chess))
```
Here, I've used the `between()` function which is a shortcut for otherwise writing `x >= left & x <= right`. You can play around with the margin to see how the result changes.
## Additional resources
### Datacamp
- [Foundations of probability in R](https://www.datacamp.com/courses/foundations-of-probability-in-r)
## Session info
Information about this R session including which version of R was used, and what packages were loaded.
```{r}
sessionInfo()
```