Professional Documents
Culture Documents
1 Solving Probability Problems With R: # We Can Use The Built-In Function "Sample" As Follows
1 Solving Probability Problems With R: # We Can Use The Built-In Function "Sample" As Follows
1 Solving Probability Problems With R: # We Can Use The Built-In Function "Sample" As Follows
1. Simulate 100 tosses of a fair coin, and count the frequency of each possible outcome.
Solution:
# We can use the built-in function "sample" as follows:
coin_tosses <- sample(c("H","T"), 100, replace=TRUE)
coin_tosses
##
##
##
##
##
##
[1]
[18]
[35]
[52]
[69]
[86]
"T"
"H"
"T"
"T"
"H"
"H"
"H"
"H"
"T"
"T"
"T"
"H"
"T"
"H"
"T"
"T"
"H"
"H"
"H"
"H"
"H"
"T"
"H"
"T"
"T"
"H"
"T"
"T"
"H"
"H"
"T"
"T"
"H"
"T"
"H"
"H"
"T"
"T"
"H"
"H"
"T"
"H"
"H"
"T"
"T"
"T"
"H"
"H"
"T"
"H"
"H"
"H"
"T"
"T"
"H"
"H"
"T"
"H"
"T"
"H"
"T"
"T"
"T"
"H"
"H"
"H"
"H"
"H"
"T"
"T"
"H"
"T"
"T"
"H"
"H"
"H"
"T"
"T"
"H"
"T"
"H"
"H"
"T"
"H"
"T"
"H"
"H"
"H"
"T"
"H"
"T"
"T"
"H"
"T"
"T"
"H"
"T"
"T"
"T"
"T"
2. Simulate 100 throws of a fair die, and count the frequency of each possible outcome.
Solution:
die_throws <- sample(c(1:6), 100, replace=TRUE)
die_throws
##
##
##
[1] 5 6 5 4 2 5 6 4 5 3 2 5 5 1 6 2 3 2 1 5 2 4 3 3 6 5 6 4 2 3 3 6 4 5 2
[36] 6 3 1 4 3 2 4 6 2 1 5 6 4 2 3 6 3 1 6 2 5 6 4 5 2 2 3 3 1 3 1 3 6 3 3
[71] 2 3 1 5 1 6 2 2 6 5 6 1 3 3 6 1 2 2 1 3 4 4 4 1 3 3 1 6 5 4
# frequencies:
table(die_throws)
## die_throws
## 1 2 3 4 5 6
## 14 18 22 13 15 18
3. Generate the entire probability distribution of a binomially distributed random variable, with n = 10
and p = 1/5. Confirm that it is in fact a probability distribution. Calculate the expectation and check
that it obeys the correct formula.
Solution:
# Generate the probability distribution
n <- 10
p <- 1/5
pd <- dbinom(0:n, n, p)
pd
## [1] 0.1073741824 0.2684354560 0.3019898880 0.2013265920 0.0880803840
## [6] 0.0264241152 0.0055050240 0.0007864320 0.0000737280 0.0000040960
## [11] 0.0000001024
# Confirm that it is a probability distribution
sum(pd) == 1
## [1] TRUE
# Calculate the expectation:
epd <- sum(pd * (0:n))
epd
## [1] 2
# Check that it obeys the formula
epd1 <- n * p
epd1
## [1] 2
4. [handout-4b, Problem 4] Let X be the number that results from rolling a fair die. (a) What is the
expected value of X 2 ? (b) What is the variance of this random variable X?
Solution:
Page 2
p <- array(1/6, 6)
x <- 1:6
# expected value of X^2
expect_of_xsq <- sum(x^2 * p)
expect_of_xsq
## [1] 15.16667
# Variance, using the formula Var[X] = E[X^2] - (E[X])^2
expect_of_x <- sum(x * p)
var_of_x <- expect_of_xsq - expect_of_x^2
var_of_x
## [1] 2.916667
5. (handout 4b - problem 2 points) Suppose we roll 3 fair dice. Let X be the largest number among the 3
observed numbers. (a) Find the CDF F(x) and the random variable X (b) Find the PMF p(x):
Solution:
Page 3
1
1
2
8
3
27
4
5
6
64 125 216
Page 4