In: Computer Science
Simulating a conditional probability using R.
Simulating the conditional probability P(A|B) requires repeated
simulation of
the underlying random experiment, but restricting to trials in
which B occurs.
Suppose 3 dice are tossed and we want to find the probability of
the first die is 4 given that the sum is 10.
Modify the script ConditionalDice.R (you can find the R script file
from Modules on this Canvas site) to find
P(First die is 4 | Sum is 10)
Hint: the exact answer is: 5/27.
### R: Simulating a conditional probability
#Simulating the conditional probability P(A|B) requires repeated
simulation of
#the underlying random experiment, but restricting to trials in
which B occurs.
### ConditionalDice.R
### Suppoese we roll 2 dice and want to find
### P(First die is 2 | Sum is 7)
### We know that answer is: 1/6.
### In this case, we repeatly toss two dice, but the only data
that we keep
### are those pairs whose sum is 7.
n <- 60000
ctr <- 0
# ctr is the counter for the rolls when the sum is 7
simlist <- replicate(n, 0) ## Initialize list with 0's
while (ctr < n)
{
trial <- sample(1:6, 2, replace=TRUE) ## Roll 2
dice
if (sum(trial) == 7) ### Check if sum is 7
### If not, skip through and roll again
### If 7, check if first die is a 2
{
success <- if (trial[1] == 2) 1 else 0
ctr <- ctr + 1
simlist[ctr] <- success
### simlist records successes and failures only
for
### dice rolls that sum to 7
}
}
### Simulated result
simlist
mean(simlist)
n <- 60000
ctr <- 0
# ctr is the counter for the rolls when the sum is 7
simlist <- replicate(n, 0) ## Initialize list with 0's
while (ctr < n)
{
trial <- sample(1:6, 3, replace=TRUE) ## Roll 3 dice
if (sum(trial) == 10) ### Check if sum is 10
### If not, skip through and roll again
### If 10, check if first die is a 2
{
success <- if (trial[1] == 4) 1 else 0
ctr <- ctr + 1
simlist[ctr] <- success
### simlist records successes and failures only for
### dice rolls that sum to 10
}
}
### Simulated result
simlist
mean(simlist)