library(ggplot2)
library(scales)
# The Monty Hall problem
#create door combinations
a <- c(123, 132, 213, 231, 312, 321)
#create results vectors
car = integer(length = 10^5)
goat1 = integer(length = 10^5)
goat2 = integer(length = 10^5)
initial_choice = integer(length = 10^5)
open_door = integer(length = 10^5)
who_wins = character(length = 10^5)
#create 100,000 games
for (i in 1:10^5){
#set up a situation
doors <- sample(a, 1)
#randomly pick a door combination
car[i] <- doors %/% 100
#the first number is which door is the right door
goat1[i] <- (doors - car[i] * 100) %/% 10
#where is the first wrong door
goat2[i] <- doors - car[i] * 100 - goat1[i] * 10
#where is the second wrong door
initial_choice[i] <- sample(c(1, 2, 3), 1)
#have a person select a random door
#now we open the wrong door
if (initial_choice[i] == car[i]){
open_door[i] = sample(c(goat1[i], goat2[i]), 1)
#if the person is initially on the right door we randomly select one of the two wrong doors
} else if (initial_choice[i] == goat1[i]) {
open_door[i] = goat2[i]
} else {
open_door[i] = goat1[i]
} #if the person is initially on the wrong door, we open the other wrong door
#stayer remains by his initial choice and switcher changes his choice
if (initial_choice[i] == car[i]){
who_wins[i] = "Stays"
}
else {who_wins[i]="Switchs"
}
}
monty_hall = data.frame(car,
goat1,
goat2,
initial_choice,
open_door,
who_wins)
Plot results
ggplot(data = monty_hall, aes(who_wins, fill = who_wins)) +
geom_bar(aes(y = (..count..)/sum(..count..))) + #crude but effective
ylim(0, 1) +
ylab("Ratio") +
xlab("Who wins?") +
theme(legend.position = "none")