Vistat

a reproducible gallery of statistical graphics

Simulation of Coin Flipping

  • Lijia Yu (yu@lijiayu.net / GitHub / Twitter) A master candidate majoring in Bioinformatics at Beijing Institute of Genomics.

The function flip.coin() in the animation package provides a simulation to the process of flipping coins and computes the frequencies for heads and tails. Coin flipping is a well-known Bernoulli trial. When you flip a coin, there are two possible outcomes: head or tail. A fair coin has the probability 0.5 for head by definition.

Head or tail

We toss a fair coin 100 times below.

library(animation)
ani.options(nmax = 100, interval = 0.3)
par(mar = c(2, 4, 2, 2))
flip.coin(bg = "yellow")

Note the outcome is random, so if you run the code above again, you are likely to see different results, but on average you should get 50 heads and 50 tails in the long run.

Generalization

The coin here does not have to mean a coin literally. We can generalize it to an object that can produce $n$ possible outcomes. For example, three outcomes Head, Stand (a coin may stand on the table) and Tail with probabilities 0.45, 0.1 and 0.45 respectively:

ani.options(nmax = 100, interval = 0.3)
par(mar = c(2, 4, 2, 2))
flip.coin(faces = c("Head", "Stand", "Tail"), type = "n", prob = c(0.45, 
  0.1, 0.45), col = c(1, 2, 4))

Meta

Keywords: Categories: Reviewer: You can find the R Markdown source document in the vistat repository on GitHub.