Submission Instructions: For this lab, please submit your R script (.R file), not a knitted R Markdown document. Your script should contain the code you used to answer each question. For questions that ask you to report a result, make a comparison, or explain something, include your answers as comments (#) in your script. I should be able to see both your code and your responses without having to run everything myself.

Preamble

One of the useful things we can do with R is simulate random events. We can simulate things like rolling dice, flipping coins, or randomly selecting observations from a dataset. By repeating these experiments many times, we can investigate how random processes behave and estimate probabilities that might otherwise be difficult to calculate.

For example, suppose we flip a fair coin 10,000 times. We know that the theoretical probability of getting heads is 0.5, but we can use R to simulate these flips and see how closely our results match this probability.

flips = sample(c("Heads", "Tails"), 10000, replace = TRUE)

mean(flips == "Heads")
## [1] 0.4999

Our simulated probability should be reasonably close to 0.5. If we repeat the simulation, we’ll generally obtain a slightly different result. Increasing the number of repetitions tends to make our estimates more stable (Law of Large Numbers!). This is one way that simulation can help us investigate random processes and verify results from probability theory.

Of course, computers aren’t physically flipping coins or rolling dice. Instead, they typically use a pseudorandom number generator (PRNG), an algorithm that produces a sequence of numbers that behaves like a random sequence. Because this process is deterministic, we can reproduce the same sequence by specifying a starting value called a seed. We’ll explore this later in the lab.

Lab

Random Sampling with sample()

The base R function sample() randomly selects values from a vector. Its most important arguments are x, the values we want to sample from; size, how many values we want; and replace, whether a value can be selected more than once.

For example, we can simulate rolling a six-sided die:

sample(1:6, size = 1)
## [1] 4

What if we want to roll that die ten times?

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

We use replace = TRUE because rolling a 6 does not prevent us from rolling another 6. Without replacement, a selected value is removed from the pool of available values. In particular, asking R to sample ten values from 1:6 without replacement would not work: there are only six distinct values available.

Question 1

A. Simulate 100 rolls of a fair six-sided die. Store the results in a vector.

B. Calculate the proportion of your rolls that resulted in a 6. How does this compare with the probability of rolling a 6 on a fair die?

C. Repeat Parts A and B using 10,000 rolls instead of 100. Compare your two estimates with the theoretical probability of \(\frac{1}{6}\). Which estimate is closer?


Drawing Cards

A standard deck contains 52 cards: thirteen ranks in each of four suits. We can create a vector representing the deck by combining the ranks and suits:

ranks = c("A", 2:10, "J", "Q", "K")
suits = c("Hearts", "Diamonds", "Clubs", "Spades")
deck = paste(rep(ranks, each = 4), rep(suits, times = 13))

head(deck)
## [1] "A Hearts"   "A Diamonds" "A Clubs"    "A Spades"   "2 Hearts"  
## [6] "2 Diamonds"
length(deck)
## [1] 52

When drawing cards from a deck, once the deck is defined as a vector, we can just go back to using sample().

# 5 cards from the deck
sample(deck, size = 5, replace = FALSE)
## [1] "K Spades"   "3 Clubs"    "K Diamonds" "Q Spades"   "J Clubs"

Question 2

Suppose for now we ignore the suits of cards and construct this deck.

ranks = c("Ace", "2", "3", "4", "5", "6", "7",
          "8", "9", "10", "Jack", "Queen", "King")

deck = rep(ranks, each = 4)

A. Simulate drawing five cards from this deck without replacement.

B. Use a logical condition and sum() to determine how many Aces are in your hand.

C. Suppose we consider a hand successful if it contains at least one Ace. Write an expression that returns TRUE if your hand is successful and FALSE otherwise.

D. Write a for-loop to draw 1000 hands and check if each contains an Ace. Does a five-card hand usually contain an Ace? Explain why you think this is the case.

E. What would change if you sampled with replacement? Could you obtain a hand that would be impossible when drawing from a real deck?


Sampling Observations from Data Frames

Random sampling is not limited to dice and cards. We can also randomly select observations from a dataset. Recall that we can subset a data frame using row indices. For example, the following selects the first ten rows of the penguins data frame:

penguins[1:10, ]
## # A tibble: 10 × 8
##    species island    bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
##    <fct>   <fct>              <dbl>         <dbl>             <int>       <int>
##  1 Adelie  Torgersen           39.1          18.7               181        3750
##  2 Adelie  Torgersen           39.5          17.4               186        3800
##  3 Adelie  Torgersen           40.3          18                 195        3250
##  4 Adelie  Torgersen           NA            NA                  NA          NA
##  5 Adelie  Torgersen           36.7          19.3               193        3450
##  6 Adelie  Torgersen           39.3          20.6               190        3650
##  7 Adelie  Torgersen           38.9          17.8               181        3625
##  8 Adelie  Torgersen           39.2          19.6               195        4675
##  9 Adelie  Torgersen           34.1          18.1               193        3475
## 10 Adelie  Torgersen           42            20.2               190        4250
## # ℹ 2 more variables: sex <fct>, year <int>

To select random rows, we first need to generate random row indices. The function nrow() tells us how many observations are in a data frame:

nrow(penguins)
## [1] 344

When we give sample() a single positive integer, R samples from the integers starting at 1 and ending at that number. Thus:

sample(nrow(penguins), 10)
##  [1] 192  11 173 215 219 133 136 330 128 287

returns ten randomly selected row indices, not ten penguin observations. We can store those indices and use them to retrieve the corresponding rows:

rows = sample(nrow(penguins), 10)
penguins[rows, ]
## # A tibble: 10 × 8
##    species   island   bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
##    <fct>     <fct>             <dbl>         <dbl>             <int>       <int>
##  1 Adelie    Torgers…           38.5          17.9               190        3325
##  2 Gentoo    Biscoe             50.7          15                 223        5550
##  3 Gentoo    Biscoe             52.1          17                 230        5550
##  4 Adelie    Torgers…           34.4          18.4               184        3325
##  5 Chinstrap Dream              47.6          18.3               195        3850
##  6 Adelie    Biscoe             37.6          17                 185        3600
##  7 Gentoo    Biscoe             49.9          16.1               213        5400
##  8 Gentoo    Biscoe             42.7          13.7               208        3950
##  9 Gentoo    Biscoe             45.4          14.6               211        4800
## 10 Adelie    Torgers…           39.7          18.4               190        3900
## # ℹ 2 more variables: sex <fct>, year <int>

Or we can combine the two steps:

penguins[sample(nrow(penguins), 10), ]
## # A tibble: 10 × 8
##    species   island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
##    <fct>     <fct>           <dbl>         <dbl>             <int>       <int>
##  1 Chinstrap Dream            46.1          18.2               178        3250
##  2 Adelie    Dream            33.1          16.1               178        2900
##  3 Chinstrap Dream            43.5          18.1               202        3400
##  4 Gentoo    Biscoe           48.4          14.4               203        4625
##  5 Chinstrap Dream            45.5          17                 196        3500
##  6 Adelie    Biscoe           39.6          20.7               191        3900
##  7 Chinstrap Dream            42.4          17.3               181        3600
##  8 Adelie    Dream            41.1          17.5               190        3900
##  9 Chinstrap Dream            45.4          18.7               188        3525
## 10 Gentoo    Biscoe           45.2          14.8               212        5200
## # ℹ 2 more variables: sex <fct>, year <int>

The dplyr package also provides slice_sample(), which performs the same kind of operation more directly:

penguins |>
  slice_sample(n = 10)
## # A tibble: 10 × 8
##    species   island   bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
##    <fct>     <fct>             <dbl>         <dbl>             <int>       <int>
##  1 Gentoo    Biscoe             46.3          15.8               215        5050
##  2 Chinstrap Dream              46.5          17.9               192        3500
##  3 Adelie    Torgers…           34.6          17.2               189        3200
##  4 Gentoo    Biscoe             44.9          13.8               212        4750
##  5 Adelie    Biscoe             39.6          20.7               191        3900
##  6 Gentoo    Biscoe             49.2          15.2               221        6300
##  7 Adelie    Torgers…           37.8          17.3               180        3700
##  8 Adelie    Torgers…           36.7          18.8               187        3800
##  9 Gentoo    Biscoe             49.5          16.2               229        5800
## 10 Adelie    Biscoe             37.8          18.3               174        3400
## # ℹ 2 more variables: sex <fct>, year <int>

These approaches are useful whenever we want to inspect a random subset of observations. We can also sample with replacement, allowing an observation to appear more than once in the new sample. Repeatedly drawing samples with replacement from an observed dataset is the basis of a statistical method called bootstrapping (which you may have briefly seen in 209). In bootstrapping, we use the data we collected to construct many new samples and study how a statistic, such as a sample mean, varies from one sample to another.

Question 3

The penguins dataset contains measurements collected from several species of penguins. Suppose we’re interested in estimating the average body mass of penguins using only a randomly selected subset of the observations.

A. Randomly select 10 observations from penguins and calculate their average body mass. Be sure to account for missing values.

B. Repeat the process using a random sample of 100 observations. Compare your two estimates with the average body mass calculated using the entire dataset.

C. Run your code several times. Which sample size tends to produce estimates closer to the overall average? Why do you think this happens?


Reproducibility with set.seed()

Every time you run the previous examples, you will generally get different results. That is useful for simulation, but it can make it difficult to reproduce an analysis or compare your results with someone else’s.

The function set.seed() tells R where to begin in its pseudorandom number sequence. If we use the same seed and then run the same random operations in the same order, we obtain the same results:

set.seed(123)
sample(1:20, 5)
## [1] 15 19 14  3 10
set.seed(123)
sample(1:20, 5)
## [1] 15 19 14  3 10

The particular number we choose as the seed is not important; what matters is using the same one when we want reproducible results. Setting a seed does not make the experiment nonrandom in the statistical sense. It makes the simulated sequence reproducible.


Repeating Experiments with replicate()

So far, we’ve used sample() to generate multiple random observations. Sometimes, though, we want to repeat an entire experiment and record a summary from each repetition.

Suppose an experiment consists of rolling a six-sided die ten times and counting the number of sixes:

sum(sample(1:6, 10, replace = TRUE) == 6)
## [1] 3

The expression produces one result: the number of sixes in that set of ten rolls. We can repeat the whole experiment 100 times using replicate():

set.seed(123)
counts = replicate(100, sum(sample(1:6, 10, replace = TRUE) == 6))

head(counts)
## [1] 3 1 2 0 1 1
table(counts)
## counts
##  0  1  2  3  4  5 
## 16 37 23 17  5  2

Each element of counts is the result of a different experiment involving ten rolls. This differs from simply generating 100 die rolls, because we’re interested in the number of sixes within each group of ten.

The benefit of replicate is that it essentially functions as a for-loop without having to write one =)

Question 4

A. Modify the preceding example to simulate an experiment in which you roll a six-sided die 20 times and count the number of sixes. Repeat this experiment 1,000 times using replicate().

B. Estimate the probability of obtaining at least five sixes in an experiment by calculating the proportion of your 1,000 repetitions that meet this condition.

C. Choose a seed and rerun your code from Parts A and B. Verify that you can reproduce your results by setting the same seed before repeating the simulation.


Sampling from Probability Distributions

So far, we have simulated randomness by sampling from collections of values that we explicitly specified. R can also generate random observations from specified probability distributions (like Normal, t-, F).

Recall from your earlier statistics courses that random variables can be discrete or continuous. Discrete random variables have a countable set of possible outcomes, such as the number of heads in ten coin flips. Continuous random variables can take values throughout an interval, such as a person’s height.

R provides families of functions for many distributions. We’ll look at three examples.

Uniform Distribution

A continuous uniform distribution assigns equal probabilities to intervals of equal length within its range. The function runif() generates random observations from this distribution:

uniform_values = runif(1000, min = 0, max = 1)
hist(uniform_values)

The histogram should be approximately flat, though the heights of individual bars will vary due to randomness.

Normal Distribution

You’ve likely encountered the normal distribution, with its familiar bell-shaped curve. The function rnorm() generates observations from a normal distribution, given a mean and standard deviation:

normal_values = rnorm(1000, mean = 70, sd = 10)
hist(normal_values)

Binomial Distribution

A binomial distribution describes the number of successes in a fixed number of independent trials, where each trial has the same probability of success. For example, if we flip a fair coin ten times and count the heads, the number of heads follows a binomial distribution.

rbinom(1, size = 10, prob = 0.5)
## [1] 3

This generates the number of heads in one experiment consisting of ten coin flips. To repeat that experiment 1,000 times:

heads = rbinom(1000, size = 10, prob = 0.5)
hist(heads, breaks = seq(-0.5, 10.5, by = 1))

Notice that these outcomes are integers from 0 to 10. Unlike the uniform and normal examples, the binomial distribution is discrete. The same idea applies to our earlier experiment of counting sixes among 20 die rolls: there are 20 independent trials, each with a probability of success of 1/6.

rbinom(1000, size = 20, prob = 1/6)
##    [1]  2  5  2  4  1  5  5  5  0  1  2  2  1  4  0  5  3  4  6  3  6  2  2  7
##   [25]  2  5  2  4  4  2  0  3  4  3  3  3  2  2  0  3  3  7  1  4  3  0  2  4
##   [49]  3  5  4  3  2  3  2  3  2  6  2  4  1  3  2  5  3  2  3  2  4  5  6  4
##   [73]  4  4  6  8  2  2  6  3  4  5  1  5  4  0  1  3  5  3  2  6  3  4  2  2
##   [97]  2  3  6  3  5  1  4  2  3  1  5  6  4  1  6  2  5  4  3  4  3  4  2  4
##  [121]  3  5  3  3  5  4  0  4  2  7  3  4  1  2  6  4  3  4  2  3  2  2  5  4
##  [145]  7  2  3  3  3  3  2  4  6  2  4  6  0  3  2  3  3  5  2  5  3  4  1  5
##  [169]  4  3  4  7  5  6  4  3  6  4  3  3  0  3  3  1  4  2  3  3  6  4  5  3
##  [193]  4  2  3  6  2  2  3  5  4  3  5  2  3  1  2  4  8  5  4  3  2  7  5  7
##  [217]  3  4  5  3  3  4  3  2  3  4  4  6  2  2  2  3  3  3  4  3  3  2  4  2
##  [241]  2  1  1  4  7  5  4  4  3  4  3  1  5  5  3  4  4  5  3  3  2  1  4  5
##  [265]  3  2  6  3  1  6  3  3  3  2  2  5  5  2  3  2  1  5  2  3  2  3  5  0
##  [289]  8  5  2  4  3  1  4  3  8  3  0  0  2  1  1  3  3  2  3  3  2  1  7  2
##  [313]  4  6  8  4  5  1  1  1  2  3  4  2  2  1  4  5  4  4  4  4  3  2  2  3
##  [337]  1  1  4  3  5  4  3  5  5  3  7  2  7  3  2  5  4  3  2  3  4  3  3  3
##  [361]  4  3  2  3  5  1  3  5  2  4  3  4  3  7  6  4  2  2  8  3  2  3  4  1
##  [385]  0  3  2  0  4  5  4  1  4  4  2  3  1  3  2  5  3  6  4  3  5  3  3  4
##  [409]  3  4  3  4  3  6  6  6  2  3  3  2  3  6  1  4  2  2  4  1  4  4  5  2
##  [433]  2  3  6  1  2  4  1  7  0  3  5  2  4  3  3  6  3  3  6  1  5  2  2  1
##  [457]  1  2  5  3  4  6  2  4  4  2  0  3  2  3  4  2  3  3  1  2  5  3  5  5
##  [481]  2  4  3  4  4  6  5  6  2  0  2  4  4  3  1  1  2  8  5  3  1  2  1  4
##  [505]  3  5  3  3  1  3  4  5  2  3  3  4  3  3  4  2  3  2  3  6  6  4  4  6
##  [529]  4  6  4  2  4  3  6  6  3  3  4  4  7  3  2  5  6  4  2  3  6  3  2  3
##  [553]  2  3  5  0  5  2  4  4  4  4  4  4  7  5  1  3  2  3  1  1  5  6  3  3
##  [577]  3  3  6  4  2  3  7  4  1  1  6  5  4  2  3  2  3  5  6  5  6  3  1  2
##  [601] 10  3  8  4  2  6  3  5  2  6  3  1  5  2  3  4  4  3  6  2  0  2  2  6
##  [625]  3  2  2  1  5  1  2  3  3  5  5  6  5  6  3  3  3  3  1  4  2  5  8  1
##  [649]  3  4  5  4  3  6  4  3  3  7  6  2  2  3  1  7  5  4  3  2  6  3  3  3
##  [673]  6  3  4  2  3  5  4  5  2  1  6  3  3  2  0  2  2  4  1  2  0  2  3  3
##  [697]  4  6  2  7  1  4  2  2  1  2  4  3  4  2  1  4  2  3  5  0  3  1  3  7
##  [721]  4  5  4  3  5  3  5  3  1  3  3  3  4  2  3  1  0  1  2  2  5  3  3  4
##  [745]  1  5  4  5  3  4  4  4  7  2  1  3  2  3  3  4  0  2  3  5  2  2  7  3
##  [769]  0  1  6  3  5  5  5  4  3  3  2  4  5  4  2  3  4  1  4  4  5  2  2  5
##  [793]  2  5  4  2  4  1  6  5  4  6  3  5  5  2  2  2  5  4  2  5  4  3  1  2
##  [817]  4  6  1  3  3  3  1  5  2  3  2  6  4  3  2  4  2  2  5  3  6  5  5  4
##  [841]  1  3  6  1  1  4  3  8  4  5  3  8  3  7  3  4  4  5  4  0  1  6  3  4
##  [865]  4  6  4  2  3  4  2  4  1  6  2  2  3  3  2  2  4  3  4  4  1  3  4  2
##  [889]  4  6  3  3  3  1  3  2  3  3  2  1  4  3  1  3  2  1  2  3  2  3  3  5
##  [913]  2  3  2  2  3  4  1  4  3  3  4  2  1  3  1  2  7  1  4  4  3  3  3  3
##  [937]  4  7  3  3  2  2  3  2  3  3  3  3  2  1  5  3  3  4  2  3  4  1  4  4
##  [961]  3  5  4  4  2  4  3  1  2  5  1  3  3  3  4  6  2  3  3  5  1  0  2  3
##  [985]  5  3  1  1  1  5  3  7  4  2  5  4  8  1  5  7

This simulates the same kind of outcome as our earlier replicate() example, but directly through a probability distribution rather than by simulating every individual die roll.


The d, p, and r Functions

R uses a consistent naming convention for working with probability distributions. We’ve already used functions beginning with r to generate random observations. The d and p prefixes let us evaluate distribution functions and calculate probabilities.

Prefix What it does Example
r Generates random observations rnorm()
d Evaluates a probability mass or density function dnorm()
p Calculates the probability of an outcome less than or equal to a specified value pnorm()

For example, consider a standard normal distribution (mean 0, standard deviation 1):

rnorm(10, mean = 0, sd = 1)
##  [1]  0.6714535  2.0279241 -0.3009243 -0.2133494  0.2532701 -1.4200880
##  [7] -1.8354367  1.8067894 -0.5749957 -0.4578809
dnorm(1, mean = 0, sd = 1)
## [1] 0.2419707
pnorm(1, mean = 0, sd = 1)
## [1] 0.8413447

The first function generates ten random observations. The second evaluates the density function at 1; because the normal distribution is continuous, this value is not the probability of obtaining exactly 1. The third calculates the probability of observing a value less than or equal to 1.

For a discrete distribution such as the binomial, the d function gives the probability of an exact outcome. Compare:

dbinom(5, size = 10, prob = 0.5)
## [1] 0.2460938
pbinom(5, size = 10, prob = 0.5)
## [1] 0.6230469

The first gives the probability of obtaining exactly five heads in ten fair coin flips. The second gives the probability of obtaining five or fewer heads. We can also find probabilities of outcomes above a threshold by subtracting an appropriate cumulative probability from 1.

Question 5

A. Suppose you flip a fair coin 20 times. Use dbinom() to calculate the probability of obtaining exactly 10 heads.

B. Use pbinom() to calculate the probability of obtaining 10 or fewer heads. Explain how this differs from Part A.

C. Suppose a random variable follows a normal distribution with mean 100 and standard deviation 15. Use pnorm() to calculate the probability that the variable is less than 115.

Question 6

Suppose we have a coin that lands on heads with probability 0.65. We flip the coin 1,000 times and want to know how likely we are to obtain at least 700 heads.

A. Use rbinom() to simulate this experiment 10,000 times. Store the resulting numbers of heads in a vector.

B. Estimate the probability of obtaining at least 700 heads by calculating the proportion of simulated experiments in which this happened.

C. Use pbinom() to calculate the theoretical probability of obtaining at least 700 heads. Hint: pbinom() calculates probabilities of outcomes at or below a value. Think about which outcomes you need to subtract from 1. Compare your result with Part B.

Challenge Problems (Required)

Question 7: Rolling Dice

In tabletop games such as Dungeons & Dragons or Pathfinder, dice are often described using the notation XdY, where X represents the number of dice rolled and Y represents the number of sides on each die. For example, 3d6 means rolling three six-sided dice.

A. Write a function called roll_dice() that takes two arguments, X and Y, and simulates rolling X dice with Y sides each. Your function should return a vector containing the individual die results, rather than their sum.

B. Test your function by rolling 4d8 and 2d20.

C. Fireball. Your friend’s clever wizard uses the Fireball spell on a group of bandits. Use your function and sum to roll 8d6 and calculate how much damage the spell deals to the bandits.

Question 8: Rolling with Advantage

In Dungeons & Dragons, players often roll a 20-sided die (a d20) to help determine whether they successfully complete a task, such as attacking a monster or climbing a particularly dangerous cliff face without falling. In particularly favorable circumstances, a player may roll with Advantage, allowing them to roll two d20s and take the higher result (this is called Fortune in Pathfinder). This effectively gives them two chances to obtain a good roll.

A. Using your roll_dice() function from Question 7, simulate 1,000 ordinary d20 rolls and 1,000 rolls with Advantage. Store the results in separate vectors.

B. Create graphs comparing the distributions of the ordinary rolls and rolls with Advantage. Describe how the distributions differ. Try to use the same horizontal axis and comparable scales so that the difference is easy to see.

C. Suppose a player needs to roll a 15 or higher to succeed at a task. Use your simulated results to estimate the probability of success with and without Advantage. How much does Advantage improve their chances?