Created
June 27, 2020 02:52
-
-
Save tmasjc/1d8685f0385b5524120720494f2f469b to your computer and use it in GitHub Desktop.
A spurious example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## the game goes like this, | |
| ## head +1 point and tail -1 point | |
| ## we flip 3 coins and count the score | |
| ## is there a correlation between them? | |
| library(tidyverse) | |
| library(ggthemes) | |
| set.seed(1234) | |
| coins = 4 | |
| flips = 1e3 | |
| calc_score <- function(vec) { | |
| map_dbl(1:length(vec), | |
| ~ sum(vec[1:.x] == 1) - sum(vec[1:.x] == 0)) | |
| } | |
| f <- expression(rbinom(flips, 1, 0.5)) | |
| res <- rerun(coins, calc_score(eval(f))) %>% | |
| set_names(paste("coin", 1:coins)) %>% | |
| bind_rows() %>% | |
| mutate(flip = row_number()) | |
| df <- res %>% | |
| pivot_longer(cols = -flip, | |
| names_to = "coin", | |
| values_to = "score") | |
| df %>% | |
| ggplot(aes(flip, score, col = coin)) + | |
| geom_line(aes(group = coin), size = 1.1) + | |
| coord_cartesian(ylim = c(-60, 60)) + | |
| scale_color_wsj() + | |
| theme_minimal(base_family = "Menlo") + | |
| theme(title = element_text(size = 20)) + | |
| labs(x = "# Flips", y = "Score", col = "Coin", | |
| title = "Tossing 4 Coins Randomly", | |
| subtitle = "an example of spurious correlation") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment