Skip to content

Instantly share code, notes, and snippets.

@tmasjc
Created June 27, 2020 02:52
Show Gist options
  • Select an option

  • Save tmasjc/1d8685f0385b5524120720494f2f469b to your computer and use it in GitHub Desktop.

Select an option

Save tmasjc/1d8685f0385b5524120720494f2f469b to your computer and use it in GitHub Desktop.
A spurious example
## 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