Chapter 4 Section 1 Exercise 11
Simulate the Monty Hall problem. Carefully state any assumptions that you have made when writing the program. Which version of the problem do you think that you are simulating?
Stay Strategy
## Using the stay strategy, the win percentage was 33.9%

Switch Strategy
## Using the switch strategy, the win percentage was 67.7%

Random Strategy
## Using the random strategy, the win percentage was 48.7%

Inspiration for this solution came from R-bloggers - Monty Hall by Simulation in R.
Article
Simulation Function
rm(list=ls())
monty<-function(strat='stay',N=1000,print_games=FALSE)
{
doors<-1:3 #initialize the doors behind one of which is a good prize
win<-0 #to keep track of number of wins
for(i in 1:N)
{
prize<-floor(runif(1,1,4)) #randomize which door has the good prize
guess<-floor(runif(1,1,4)) #guess a door at random
## Reveal one of the doors you didn't pick which has a bum prize
if(prize!=guess)
reveal<-doors[-c(prize,guess)]
else
reveal<-sample(doors[-c(prize,guess)],1)
## Stay with your initial guess or switch
if(strat=='switch')
select<-doors[-c(reveal,guess)]
if(strat=='stay')
select<-guess
if(strat=='random')
select<-sample(doors[-reveal],1)
## Count up your wins
if(select==prize)
{
win<-win+1
outcome<-'Winner!'
}else
outcome<-'Losser!'
if(print_games)
cat(paste('Guess: ',guess,
'\nRevealed: ',reveal,
'\nSelection: ',select,
'\nPrize door: ',prize,
'\n',outcome,'\n\n',sep=''))
}
#Print the win percentage of your strategy
cat(paste('Using the ',strat,' strategy, the win percentage was ',win/N*100,'%\n',sep=''))
# Add a nice bar plot
x <- c("win","lose")
y <- c(win, 1000-win)
montydata <- data.frame(x,y)
p <-ggplot(montydata, aes(x, y)) + geom_col() + scale_color_fivethirtyeight() + theme_fivethirtyeight()
p
}