Simulating Random Experiments with the sample function

We can use the sample function simulate tossing a coin. This function takes the arguments:

By default, every element of the vector has equal probability. However, you can use the prob argument to define a vector of probability weights for obtaining the elements of the vector being sampled.

Building Blocks

Example 1: Tossing Coins

A) Toss a coin once

sample(c("HEADS", "TAILS"), size=1)
## [1] "TAILS"

B) Toss a coin three times

Now we need to use the replace argument so that HEADS and TAILS are possible outcomes for each random experiment.

sample(c("HEADS", "TAILS"), size=3, replace=TRUE)
## [1] "HEADS" "TAILS" "HEADS"

Example 2: Rolling Dice

A) Roll a D6 once

Using the colon (A:B) will give all consecutive integers between the starting number (A) and the ending (B).

# integers
1:6
## [1] 1 2 3 4 5 6
# D6
sample(1:6, size=1)
## [1] 2

B) Roll a D6 three times

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

Practice Questions:

  • Q1: Simulate one roll of a D12.

  • Q2: (Catan) Simulate the sum of two D6.

Evaluating the Probability of Events

We can use simulations to assess the long run average (or probabilities) of the occurrence of events. This is known as the empirical probablity.

Example 3: Odd Number of Heads

Toss a fair coin four times. Let \(E\) be the event of observing an odd number of heads. Toss a coin four times and report the occurrence of \(E\).

Let’s break this problem down…

Step 1: Toss a coin four times
n<-4

## 1: HEADS
## 0: TAILS
toss<-sample(c(0,1),size=n, replace=TRUE)
toss
## [1] 0 1 1 1
Step 2: Count how many heads
sum(toss)
## [1] 3
Step 3: Check if there is an odd number of heads

To accomplish this we can use modular arithmetic!

# if 0, then even
# if 1, then odd 

sum(toss)%%2
## [1] 1
Step 4: Use a loop to repeat
nsim<-1000
odd<-c()
for(i in 1:nsim){
  toss<-sample(c(0,1),size=n, replace=TRUE)
  this_odd<-sum(toss)%%2
  odd<-c(odd, this_odd)
}
Step 4: Find the probability

Since odd is a vectors of 0’s and 1’s the average will be the empirical probability of observing an odd number of heads!

mean(odd)
## [1] 0.493

Is this close to what you were expecting?