sample
functionWe can use the sample
function simulate tossing a coin. This function takes the arguments:
x
: either a vector of one or more elements from which to choose, or a positive integersize
: a non-negative integer giving the number of items to choosereplace
: should sampling be with replacement?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.
sample(c("HEADS", "TAILS"), size=1)
## [1] "TAILS"
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"
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
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.
We can use simulations to assess the long run average (or probabilities) of the occurrence of events. This is known as the empirical probablity.
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\).
n<-4
## 1: HEADS
## 0: TAILS
toss<-sample(c(0,1),size=n, replace=TRUE)
toss
## [1] 0 1 1 1
sum(toss)
## [1] 3
To accomplish this we can use modular arithmetic!
# if 0, then even
# if 1, then odd
sum(toss)%%2
## [1] 1
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)
}
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?