The sample command

The function sample() lets us pick random values. This is very useful in probability, because it allows us to simulate experiments like coin flips, die rolls, or drawing cards.

The pattern is:

sample(x, size = n, replace = FALSE)

Example: coin flip

This chooses either heads (H) or tails (T) at random:

sample(c("H", "T"), size = 1)
[1] "H"

Example: die roll

This rolls a fair die twenty times:

sample(1:6, size = 20, replace = TRUE)
 [1] 6 3 2 4 3 3 2 1 4 1 2 6 5 1 1 4 5 4 4 5

We need replace = TRUE here, because after rolling a die, the next roll can be the same number again.

Example: Spotify shuffle

Here’s my playlist:

playlist <- c("Ramble On",
              "It's Raining Men",
              "Tears",
              "Tiptoe Through the Tulips",
              "Gangsta's Paradise",
              "Days of Wine and Roses")

There are 6 songs, so if I generate a sample of size 6 without replacement, I will ultimately draw each song exactly once, but in a random order:

sample(playlist, size = length(playlist), replace = FALSE)
[1] "Tears"                     "Tiptoe Through the Tulips"
[3] "Gangsta's Paradise"        "Ramble On"                
[5] "Days of Wine and Roses"    "It's Raining Men"