0

I’m trying to replicate the Monty hall game and when I run this function even though I assign the 3 values to results car, host and player, when the player samples the same as the car I get 4 values returned to results. I don’t understand this behavior.

switch <- FALSE
start_game <- function(switch) {
  results <- NULL
  doors <- c(1, 2, 3)
  car <- sample(doors, size = 1, replace = TRUE)
  player <- sample(doors, size = 1, replace = FALSE)
  host <- doors[-c(player, car)]
  results <- c(car, player, host)
  results
}
start_game(switch)
alz chow
  • 19
  • 4
  • 1
    if both car and player are 1, then when you do `doors[,-c(1,1)]` you are only removing the first element so `host` is `c(2,3)` then you get `(1, 1, 2, 3)` for `results. That's the behavior you are seeing. You need the host to choose from one of the two possible values. – MrFlick Nov 05 '20 at 19:06
  • I tried wrapping the host line in sample and it’s sampling wrong. Do you have any suggestions? – alz chow Nov 05 '20 at 19:16
  • 1
    you need to be careful when sampling from a vector of length 1. See: https://stackoverflow.com/questions/13990125/sample-from-vector-of-varying-length-including-1 – MrFlick Nov 05 '20 at 19:30
  • 1
    You might just need an `if` statement in there. I think I remember coming across this too: https://github.com/QuinnAsena/monty_hall/blob/master/monty_hall_function.R – QAsena Nov 05 '20 at 19:45
  • https://www.r-bloggers.com/2012/02/monty-hall-by-simulation-in-r/ – QAsena Nov 05 '20 at 20:01

0 Answers0