library(mosaic)Coins Exercise
NOTE: we will get different results every time we run this code, unless we “Set the seed” of the random number generator (i.e., use the same starting point each time). We can force R to do this using:
set.seed(427232) # Any number could be used here...We can simulate 6 tosses of a single coin (with probability of head = 0.5) as follows:
rflip(n=6, prob=0.5)
Flipping 6 coins [ Prob(Heads) = 0.5 ] ...
H T T T H H
Number of Heads: 3 [Proportion Heads: 0.5]
Or, we can use rbinom in R. Some notes about rbinom:
- n in this case refers to the number of flippers (not the number of coin tosses)
- size is the number of coin tosses (by each flipper)
- rbinom returns the number of heads
So, rbinom(n=1, prob = 0.5, size = 6) returns the number of heads when a single person (n=1) tosses a coin 6 times (size=6)
rbinom(n=1, prob=0.5, size=6)[1] 2
With rbinom, we can easily ask questions about what we might see with multiple coin tossers. We can simulate 20 coin tossers, each tossing the coin 6 times
rbinom(n=21, prob=0.5, size=6) [1] 3 2 3 3 2 2 4 5 4 3 3 3 4 4 4 2 3 2 3 3 3
What is the probability of getting 0, 1, 2, …, heads? Although there is an analytical formula that we could use, lets explore this question using simulations. Lets simulate 10,000 coin tossers and see how many toss 0, 1, 2, …, 6 heads on their 6 tosses
tally(rbinom(10000, prob=0.5, size=6), format="proportion") X
0 1 2 3 4 5 6
0.0151 0.0938 0.2279 0.3214 0.2357 0.0914 0.0147
There is a statistical distribution, called the binomial distribution, that describes these probabilities
dbinom(0:6, prob=0.5, size=6) [1] 0.015625 0.093750 0.234375 0.312500 0.234375 0.093750 0.015625
So, about 3% of the time, we should expect to get 0 or 6 heads out of 6!
Distribution of the max or min
So, 3% of the time, with a single flipper, we might get a 0 or 6. But… I picked out the person with the most extreme result (out of 20 flippers). That changes things! We can simulate the process of:
- Having 20 people each flip a fair coin 6 times
- Choosing the most extreme result
And, we can do this, say 1000 times!
extreme.flip<-do(1000)*{
flips<-rbinom(21, prob=0.5, size=6)
extreme<-pmax(6-flips, flips)
max(extreme)
}
tally(~result, data=extreme.flip, format="proportion")result
4 5 6
0.004 0.524 0.472
We see that there was > 99% chance that 1 (or more) participants would end up with 5 or 6 heads/tails!!