sample(x, size = n, replace = FALSE)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:
- The vector
xcontains the set of values we are sampling from; -
sizeis how many values we want; -
replace = FALSEmeans we don’t reuse values once they’re chosen. Setreplace = TRUEif you do want to reuse them.
Example: coin flip
This chooses either heads (H) or tails (T) at random:
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:
