-
Notifications
You must be signed in to change notification settings - Fork 1
/
iterations.qmd
2095 lines (1348 loc) · 53.2 KB
/
iterations.qmd
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "iterations"
---
This chapter review iterations, specifically how do we apply one or more functions/ transformation to each row(s) or column(s) so that you don't need to repeat yourself.
Traditionally this is done with what is called a for loop - almost all programming languages have them and R is no exception. They are not challenging but for new comers it can represent a paradiam shift in how you think about your data.
If you got to this point of the book and choose to not go further that is okay! you should smile in your accomplishment in how much you have done - you are more advanced then the lion's share of people out there and you will benefit.
However if you are willing to push yourself just a bit further you will find that enormous incremental benefits - truly the lion's share of the benefits awaits you.
This section can be intimidating for excel users not because it is hard but more than it is not as visible or transparent what is happening. Unlike Excel where you can trace what is happening in each calculation cell, here, it will be a bit more opaque which normally isn't an issue until you want to validate the findings or problem solve.
Don't worry, we are going to solve this for you.
We will show what a traditional for loop mainly because its the corner stone of what is going on here and no matter what scripting language you use this is a critical skill to learn.
However, you will see that it is super tedious. We won't be using for loops, not because there isn't anything wrong with them but more because we are lazy and want to do as little typing as possible.
There is a great speech by hadley wickam on [purr] (https://www.youtube.com/watch?v=rz3_FDVt9eg) so that you can understand the approach.
there are two frameworks that we will use
- apply()
- map()
- rowwise()
We will show numerous examples of common problems that you will most likely encourage and give you the framework and understanding of how to overcome these issues.
## What is a for loop anyways?
```{r}
#| label: for-loop
#| echo: true
#| eval: true
#| warning: false
#| message: false
#| include: true
library(tidyverse)
# select only numeric columns
df <- diamonds %>%
select(where(is.numeric))
input<- df |> as.list()
out <- vector("list", length = length(input))
for (i in seq_along(input)) {
out[[i]] <- quantile(input[[i]], 0.25, na.rm = TRUE)
}
names(out) <- names(df)
```
## Tools for your toolkit
Traditionally, you will learn how how to use for loops to do iterations
This is valid and to be honest, it is a skill you should learn as almost universal in all programming languages and other people will share code with it
We are taking a non-traditional approach and will first learn some alternative frameworks which I find more visutally helpful to learn
Then we will pivot for loops when we get fo functions
`sample()`
`replicate()`
`crossing()`
`rowwise()`
`accumulate()`
`map()`
Now there are two approaches to iteration basically what we can simplify to column wise operations vs. row wise operations.
While this may seem unusually complex, it is not, its just a matter of convention and depending on what you are trying to do one approach will be easier to use than the other but both can do anything that the other can.^[I think]
```{r}
library(tidyverse)
df <- diamonds %>%
select(where(is.numeric))
df %>%
map(.x=.,quantile,c(25:75/100)) %>%
pivot_longer(-colname) %>%
pivot_wider(names_from = colname
,values_from = value) %>%
select(-name) %>% cor
reduce(.x=1:10,~.x+.y,.init = 100,.dir = "forward")
df=map(
letters[1:3]
, ~ sample(1:10, 15, replace = T)
)
diamonds %>%
select(where(is.numeric)) %>%
map(.x=.,quantile,.25)
```
-Takes arguments and seperates that into lists (if it comes in as data frame)
- Assign each split list a variable called .x
- Takes one list at a time and applies the function to it (.x)
- Captures the results as a list or a specified output
- you an see that column title carries forward with the output so it is actually a named lists
```{r}
df <- select(diamonds,where(is.numeric))
ncol(df)
out <- vector(mode = "list",length = 7)
for (i in 1:7) {
out[i]=mean(df[[i]])
}
out
```
## Iterations with vectors and iterations
```{r}
dat <- diamonds |>
select(
where(\(x) is.numeric(x))
) |>
as.list()
mean(dat$carat)
mean(dat$depth)
mean(dat$table)
mean(dat$price)
mean(dat$x)
mean(dat$y)
mean(dat$z)
```
This is tedious to write and inefficient. What if we have 100's of objects? That would ruin our day.
So whats an alternative. We could do a for loop but we can more straight of the point just use your new favorite function `map()` family of functions.
In particular if you are working with list and vector this will simplif your life tremendously.
Le't see it action
```{r}
map(
.x=dat
,\(x) mean(x)
)
```
This is taking your list and passing through each element one by one. then with that element our function is doing something with it.
This can be helpful in its on write, such as apply arguments to columns and rows here are some common examples, however the power really shines when you have custom functions (or even just regular functions)
- Change a column from type a to type b
- Get attributes of a column
So how do we combine some of year to date learnings of tidyselect helpers, group_by()+sumamrize(), rename_with(), and our new map() friend?
Get ready to meet across(), an insanely useful and powerful verb that you will use to great satisfiction
Some of the challenges in the many models approach is how to refer to variables variables when they are part of the dataframe you are iterating over or a column from the input column or from the global environment
## how to use nested map
- if access arguments in a column just access column regularly - no prefix
- if access nested data frame you can use .x$var
- if column is quoted then use .data[[var]] and define var="quoted var"
- if column is inserted as position, you can use .data[[pos]] for position arguments
*Considerations*
- need to be mindful about the formula
- tidy friendly formula
- has data argument
- does not have data argument
- helpful links
[r4epi purr](https://www.r4epi.com/using-the-purrr-package.html)
[paulvan purr](https://paulvanderlaken.com/tag/purrr/)
framework
[jenny bc](https://jennybc.github.io/purrr-tutorial/)
[got](http://zevross.com/blog/2019/06/11/the-power-of-three-purrr-poseful-iteration-in-r-with-map-pmap-and-imap/)
[presnetation on advance purr functions](https://hendrikvanb.gitlab.io/slides/purrr_beyond_map.html#8)
[going off the map](https://hookedondata.org/posts/2019-01-09_going-off-the-map-exploring-purrrs-other-functions/)
[scraping data with purr](https://colinfay.me/purrr-web-mining/)
[rowwise purr](https://thatdatatho.com/rowwise-purrr-pmap-apply-split-apply-combine/)
[modify_if purr](https://thatdatatho.com/rowwise-purrr-pmap-apply-split-apply-combine/)
[additional purr tricks](https://www.brodrigues.co/blog/2017-03-24-lesser_known_purrr/)
[overview presentatoin](https://shannonpileggi.github.io/iterating-well-with-purrr/#/title-slide)
[additional purr functoins](https://rstudio-pubs-static.s3.amazonaws.com/602410_2171106b3c7d429b96e606e8e41960a4.html)
[examples of purr](http://joshuamccrain.com/tutorials/purrr/purrr_introduction.html)
[applied purr](https://www.weirdfishes.blog/blog/practical-purrr/)
[addition purr fucntions](https://www.emilhvitfeldt.com/post/2018-01-08-purrr-tips-and-tricks/)
```{r}
library(tidyverse)
df <- mtcars %>%
rownames_to_column("brand")
nested_df <- df %>%
group_by(gear) %>%
nest()
nested_df
```
- nested dataframe with names of columns directly in formula
```{r}
df
nested_df <- df %>%
group_by(gear) %>%
nest()
# this works
agg_fun <- function(df) {
sum(df$hp - df$drat)
}
# this doesn't work
agg_fun2 <- function(df) {
sum(hp - drat)
}
nested_df %>%
mutate(test=map_dbl(data,agg_fun))
```
- nested dataframe with names passed on as arguments in formula (unquoted)
```{r}
nested_df <- df %>%
group_by(gear) %>%
nest()
agg_fun <- function(df,var1,var2) {
x=df %>% pull({{var1}})
y=df %>% pull({{var2}})
print(sum(x - y))
}
nested_df %>%
mutate(test=map_dbl(.x=data,~agg_fun(df=.x,hp,drat)))
```
```{r}
library(tidyverse)
tibble(
x = 1:10,
y = 100:109,
r = cor(x, y))
```
- nested dataframe with with names reference from source data as arguments in formula
```{r}
nested_df <- df %>%
group_by(gear) %>%
nest()
agg_fun <- function(df,var1,var2) {
x=df %>% pull({{var1}})
y=df %>% pull({{var2}})
print(sum(x - y))
}
sel_fun <- function(df,...) {
df <- df %>%
select(any_of(c(...)))
sum(df[[1]] - df[[2]])
}
nested_df %>%
mutate(test=map_dbl(.x=data,
~sel_fun(df=.x,"qsec","mpg")
)
)
```
- nested dataframe with names names references as list from source data as arguments in formula
- trying to do aggregated function (eg return a single value) to each column of a table based on fixed value
- all_of() for quoted columns
- any_of() for quoted columns
- use this when you want to select the column names from vector
- quos or quos or quo_name()
- example
map_dfr(
.x = quos(age, ht_in, wt_lbs, bmi),
.f = continuous_stats
)
- if you use this then you pair this with {{}} - you don't need to use "" marks
[quos and purr](https://www.r4epi.com/using-the-purrr-package.html)
We haven’t seen the quos() function before. It’s another one of those tidy evaluation functions. You can type ?rlang::quos in your console to read more about it. When we can wrap a single column name with the quo() function, or a list of column names with the quos() function, we are telling R to look for them in the data frame being passed to a dplyr verb rather than looking for them as objects in the global environme
```{r}
#delcare variables
vars <- c("mpg","wt","magic")
pos <- c(2,7)
# direct and unquoted based on name or position
df %>% mutate(across(c(mpg,wt),
max))
df %>% mutate(across(c(2,7),mean))
# direct and quoted
df %>% mutate(across(c("mpg","wt"),
max))
# indirect and quoted based on name or postion
df %>% mutate(across(any_of(vars),mean))
df %>% mutate(across(all_of(pos),mean))
```
## one note
- purrr?
- vscode?
- timeseries?
```{r}
lass <- tibble(
ht_in = c(70, 63, 62, 67, 67, 58, 64, 69, 65, 68, 63, 68, 69, 66, 67, 65,
64, 75, 67, 63, 60, 67, 64, 73, 62, 69, 67, 62, 68, 66, 66, 62,
64, 68, NA, 68, 70, 68, 68, 66, 71, 61, 62, 64, 64, 63, 67, 66,
69, 76, NA, 63, 64, 65, 65, 71, 66, 65, 65, 71, 64, 71, 60, 62,
61, 69, 66, NA),
wt_lbs = c(216, 106, 145, 195, 143, 125, 138, 140, 158, 167, 145, 297, 146,
125, 111, 125, 130, 182, 170, 121, 98, 150, 132, 250, 137, 124,
186, 148, 134, 155, 122, 142, 110, 132, 188, 176, 188, 166, 136,
147, 178, 125, 102, 140, 139, 60, 147, 147, 141, 232, 186, 212,
110, 110, 115, 154, 140, 150, 130, NA, 171, 156, 92, 122, 102,
163, 141, NA)
)
cor.test(lass$ht_in,lass$wt_lbs,na.rm=TRUE) %>% broom::tidy()
```
### purrr framework
[purr gapminder example](https://www.rebeccabarter.com/blog/2019-08-19_purrr#simplest-usage-repeated-looping-with-map)
```{r}
gapminder_orig <- read.csv("https://raw.githubusercontent.com/swcarpentry/r-novice-gapminder/gh-pages/_episodes_rmd/data/gapminder-FiveYearData.csv")
gapminder_orig
```
[purr good pictures](https://dcl-prog.stanford.edu/purrr-extras.html)
## test
```{r}
eda_fun <- function(df) {
df %>% tibble(distinct=n_distinct(.x),
range=range(.x),
avg=mean(.x),
median=median(.x)
)
)
}
tibble(
name=colnames(mtcars$mpg),
class=class(mtcars$mpg),
distinct=n_distinct(mtcars$mpg),
range=paste0(range(mtcars$mpg)[1]," - ",range(mtcars$mpg)[2]),
avg=mean(mtcars$mpg),
median=median(mtcars$mpg),
missing=sum(is.na(mtcars$mpg))
)
gapminder_nested <- gapminder_orig %>%
group_by(continent) %>%
nest()
args <- tibble(cols=c("pop","lifeExp","gdpPercap"))
new_df <- gapminder_nested %>%
crossing(args)
cus_mean <- function(df,cols) {
cols <- quos(cols)
mean(df$cols)
}
new_df %>%
mutate(avg=
map2_dbl(.x=data,
.y=cols,
function(.x,.y) .x %>% pull(.y) %>% mean(.,na.rm=TRUE),.progress = TRUE
)
)
```
## purr continueod
group_map()
this works more like summarize on a grouped dataframe, whereas regular map() works more lke mutate (in that you need a mutate to add a couple)
```{r}
library(dplyr)
library(purrr)
df <- data.frame(
group = c("A", "A", "B", "B", "B"),
value = c(1, 2, 3, 4, 5)
)
df %>%
group_by(group) %>%
group_map(~ mean(.$value))
df %>%
split(.$group) %>%
map(~ mean(.$value))
df %>%
group_by(group) %>%
nest() %>%
mutate(mean = map_dbl(data, ~ mean(.$value))) %>%
select(group, mean)
remotes::install_github("TimTeaFan/loopurrr")
```
### Rowwise
An alternative approach (which actually is equal to the pmap approach if every column was used) is rowwise
#### Simple
1. use `nest_by()` to automatically group,nest and rowwise()
2. Then you can create a new column, and reference the data column to apply a function but ensure it is wrapped with `list()`
3. you can continue to use other broom function such as broom::tidy or broom::glimpse to get the model results
4. unnest to get the results
Advantage
- easy to do
Disadvantage
```{r}
dplyover::csat
lookup_vec <- set_names(names(csatraw), names(csat))
csat_named <- csatraw |>
rename(any_of(lookup_vec)) |>
select(cust_id, type, product, csat,
ends_with("rating"))
my_formula <- csat ~ postal_rating + phone_rating + email_rating +
website_rating + shop_rating
csat_named %>%
nest_by(product) %>%
mutate(mod=
list(
lm(
my_formula
,data=data
)
)
,modstat=list(broom::glance(mod))
,res=list(broom::tidy(mod))
) %>%
unnest(modstat)
```
- have to have mutiple versions of your model
### Intermediate
compare model subsegment to overall model
- for nested column, copy over values with "ALL"
- Bind with the original column so that you double the data (however one has a single catagory all)
```{r}
csat_all <- csat_named |>
mutate(product = "All") |>
bind_rows(csat_named)
```
add additional subgroups based on filtering criteria
- expand_grid
- list
- first create a list of your arguments
- if you want to filter a column in a data set you can put the filter arguments in `expr()` ofr example expr(type!= "reactive")
- you can add a default argument TRUE so that no filter is applied
- Then use `expand_grid` against the nested dataframe so that each group gets all the argument criteria
- replicate the column arguments names by taking the names of the list arguments and turning them into columns
- then you can add a column that will further filter/create subgroups by using the the `eval()` around the fitler argument list
```{r}
filter_ls <- list(
All = TRUE,
no_reactivate = expr(type != "reactivate")
)
csat_all_grps <- csat_all |>
nest_by(product) |>
expand_grid(filter_ls) |>
mutate(type = names(filter_ls),
.after = product)
csat_all_grps_grid <- csat_all_grps |>
rowwise() |>
mutate(data = list(
filter(data, eval(filter_ls))
),
.keep = "unused"
)
```
dynamically name model outputs with `list2()`
-you can not only dynamiclly name different list output but also you can give it glue like syntax in the name
```{r}
library(rlang)
csat_all_grps_grid <- csat_all_grps |>
rowwise() |>
mutate(mod = list2("{product}_{type}" := lm(my_formula, data = data)),
res = list2("{product}_{type}" := broom::tidy(mod)),
modstat = list2("{product}_{type}" := broom::glance(mod)))
```
data less grids
1. Use expand_grid() to create all the input columns that would have been created with nest_by()
2. tricky part is how to tell R when we want to refer to an input column vs the dataframe column
- by default an unquoted column referes to a dtaframe column so to refer to the list column we must use `env$colname`
-
- Pass the filter arguments through to the data portion of the formula
- first filter must be all the combinations of your master group so that input table remains whole (using env$colname)
- pass the eval(filter_args) as you did before
```{r}
product <- c(
"All", unique(csat_named$product)
)
all_grps_grid <- expand_grid(product, filter_ls) |>
mutate(type = names(filter_ls),
.after = product)
all_grps_grid |>
rowwise() |>
mutate(mod = list(
lm(my_formula,
data = filter(csat_named,
# 1. filter product categories
.env$product == "All" | .env$product == product,
# 2. filter customer types
eval(filter_ls)
)
)
)
) |>
select(! filter_ls)
```
Build formulas programmatically so that you can add incrementally add in factors
- using `expand_grid()`, add in the indepednet variables that you want to use as characters
- in the formuala argument use `reformulate()` and referncence the indepdent column variables with the dependent variable
- Create a list with a base (starting formula so you put NULL), and then terms you want to add (as quote)
- Then create a new column that just contains the formula using `update(old_formula,reformulate(c(".",update_vars)))`
```{r}
all_grps_grid_final_res <- all_grps_grid_final |>
rowwise() |>
mutate(
# dynamically name list
form = list2( "{product}_{type}_{model_spec}_{dep_vars}" :=
# update formula
update(my_formula2, # old formula
reformulate(c(".", update_vars), dep_vars)) # changes to formula
),
mod = list(
lm(form,
# create data on the fly
data = filter(csat_named_top,
.env$product == "All" | .env$product == product,
eval(filter_ls)
)
)
),
res = list(broom::tidy(mod)),
modstat = list(broom::glance(mod))
) |>
select(product:model_spec, dep_vars, mod:modstat)
```
resrouces
[Timtea Blog](https://tim-tiefenbach.de/post/2023-dplyr-many-models/)
## alterantives to columnwise iterators
dplyover::over(create multiple lead lag against a singel column)
```{r}
tibble(a = 1:25) %>%
mutate(over(c(1:3),
list(lag = ~ lag(a, .x),
lead = ~ lead(a, .x)),
.names = "a_{fn}{x}"))
```
```{r}
iris %>%
transmute(
crossover(starts_with("sepal"),
1:5,
list(lag = ~ lag(.x, .y)),
.names = "{xcol}_{fn}{y}"))
```
```{r}
iris %>%
transmute(across2(ends_with("Length"),
ends_with("Width"),
.fns = list(delta = ~ .x - .y,
sum = ~ .x + .y),
.names = "{pre}_{fn}",
.names_fn = tolower))
```
## Birthday problem
> A room has n people, and each has an equal chance of being born on any of the 365 days of the year. (For simplicity, we’ll ignore leap years). What is the probability that two people in the room have the same birthday?
```{r}
library(tidyverse)
dat <-
crossing(
people = seq(2, 75, 2)
,trial = 1:1000
) |>
mutate(
birthday = map(people, ~ sample(1:365, ., replace = TRUE))
,multiple = map_lgl(birthday, ~ any(duplicated(.)))
) |>
group_by(people) |>
summarize(chance = mean(multiple))
# Visualizing the probability
ggplot(dat, aes(people, chance)) +
geom_line() +
scale_y_continuous(labels = scales::percent_format()) +
labs(y = "Probability two have the same birthday")+
geom_smooth(method = "glm", method.args = list(family = "binomial"),
se = FALSE)
library(quantreg)
glm(chance~people, family = "binomial",data=dat)
```
## deadly board game
> While traveling in the Kingdom of Arbitraria, you are accused of a heinous crime. Arbitraria decides who’s guilty or innocent not through a court system, but a board game. It’s played on a simple board: a track with sequential spaces numbered from 0 to 1,000. The zero space is marked “start,” and your token is placed on it. You are handed a fair six-sided die and three coins. You are allowed to place the coins on three different (nonzero) spaces. Once placed, the coins may not be moved.
> After placing the three coins, you roll the die and move your token forward the appropriate number of spaces. If, after moving the token, it lands on a space with a coin on it, you are freed. If not, you roll again and continue moving forward. If your token passes all three coins without landing on one, you are executed. On which three spaces should you place the coins to maximize your chances of survival?
```{r}
roll_dice <- function(rolls=1:50,dice_number=1,max_space=50){
accumulate(rolls,.f =
function(.x,...){
out <- sample(1:6,dice_number,replace=TRUE) |> sum(.x)
if(out>max_space){
done(out)
} else {
out
}
},.init = 0)
}
crossing(
coin_placement=1:100
,trials=1:100
) |>
mutate(
roll_dice=map(trials,~roll_dice(dice_number = 3,max_space = 100))
,win_indicator=map2(roll_dice,coin_placement,~any(if_else(.y == .x,1,0)))
) |>
unnest(win_indicator) |>
group_by(coin_placement) |>
summarize(
prop_winning=mean(win_indicator)
)
crossing(people = seq(5, 100, 5),
trial = 1:100) %>%
mutate(birthday = map(people, ~ sample(365, ., replace = TRUE))) %>%
mutate(most_common = map_int(birthday, ~ max(table(.))))
sample(365,100,replace=TRUE) |> table() |> max()
```
```{r}
cumsum(sample(1:20,1,replace=TRUE))
cumsum(sample(x = 1:6, 20, replace = TRUE))
```
```{r}
tibble(
x=seq(2,100,2)
) |>
crossing(
sim=1:1000
) |>
rowwise() |>
mutate(
mod=list(sample(1:365,x,replace=TRUE))
,match=list(duplicated(mod))
,status=list(length(match[match==TRUE])>2)
) |>
unnest(status) |>
group_by(
x
) |>
summarize(
prop=mean(status)
)
```
## Grass hopper
>You are trying to catch a grasshopper on a balance beam that is 1 meter long. Every time you try to catch it, it jumps to a random point along the interval between 20 centimeters left of its current position and 20 centimeters right of its current position.
>If the grasshopper is within 20 centimeters of one of the edges, it will not jump off the edge. For example, if it is 10 centimeters from the left edge of the beam, then it will randomly jump to anywhere within 30 centimeters of that edge with equal probability (meaning it will be twice as likely to jump right as it is to jump left).
>After many, many failed attempts to catch the grasshopper, where is it most likely to be on the beam? Where is it least likely? And what is the ratio between these respective probabilities?
## Grandmom
>Each morning, your fairy godmother appears and gives you a chance to play a game. In this game, she deals 10 cards face down. Nine of the cards are winners, and one card is a loser. If you pick a winning card, you get a prize. You can then either take your prize and walk away or play again for the chance to win a second prize. But if you lose on that second play, you walk away with nothing and the game is over for the day. Each time you succeed, she invites you to play again under the same conditions (win yet another prize or lose everything).
>What strategy maximizes the average number of prizes you win each day? And what is that average?
https://fivethirtyeight.com/features/can-you-escape-the-traffic-jam-again/
```{r}
sample(1:10,size=10)
tibble(
sim=1:100
) |>
crossing(
rounds=1:10
) |>
rowwise() |>
mutate(
cards=list(sample(1:10,size=10))
,winning_card=sample(1:10,1)
) |>
unnest(cards) |>
mutate(
winning_round=if_else(cards==winning_card,1,0)
,round=row_number()
) |>
filter(
winning_round==1
,.by=c(rounds)
)
```
# birthday
>Earlier today, James’s boss was surprised to find out that not only did no one on their team have a birthday this week, but that nobody was celebrating a birthday for the entire month. With a total of 40 people on the team, the probability of this happening seemed to be miniscule.
>But was that really the case? What was the probability that none of the 40 people had birthdays this month? (For the purpose of this riddle, assume that a year consists of 12 equally long months. It’s a sufficiently good approximation!)
>Extra credit: What is the probability that there is at least one month in the year during which none of the 40 people had birthdays (not necessarily this month)?
```{r}
3*30
4*30
replicate(10000,sample(12*30,40,replace=TRUE),simplify = FALSE) |>
map_int(~if_else(any(.x%in% 90:119),0,1)) |> mean()
```
(https://fivethirtyeight.com/features/can-you-measure-the-mystery-planet/)
## race