S <- c("H", "T")Coin Toss
An introduction
What is the limiting distribution of getting heads in a coin toss? You can either land on heads or tails. Our sample space here is \(S = \{H, T\}\), and we define this in R:
We want to randomly select a head or tail: (note: I am using set.seed to get reproducible results)
set.seed(1)
sample(S, size = 1)[1] "H"
We flip our coin and we land on a head! After one toss, the relative frequency of landing on a head is \(\frac{1}{1} = 1\). Let’s flip our coin again:
sample(S, size = 1)[1] "T"
We get a tail this time. Therefore, after two tosses, the relative frequency of landing on a head is \(\frac{1}{2} = 0.5\). Let’s do one more coin toss..
sample(S, size = 1)[1] "H"
Our coin lands on a head. Therefore, after three tosses, the relative frequency of landing on a head is \(\frac{2}{3} = 0.67\).
Using a for loop to achieve multiple (1000) coin tosses
library(tidyverse)
head_vals <- c()
head_prob <- c()
for (i in 1:1000){
head_vals <- c(head_vals, sample(S, 1))
## number of times a head appears in head_vals:
n_heads <- str_count(head_vals, pattern = "H") %>% sum()
head_prob <- c(head_prob, n_heads/i)
}
tibble(sim = 1:1000, head_prob) %>%
ggplot(aes(x = sim, y = head_prob)) +
geom_line() +
geom_hline(yintercept = 0.5, colour = "red")