Get startedGet started for free

Writing a function to "switch"

Before we simulate the situation of "switch," let us first write a function to do the reveal in this context. We will then use this function in our next exercise to simulate the win probability when switching.

Recall that if the initially chosen door is correct, then the host will choose one of the other two doors at random to reveal.

If the initially chosen door is incorrect, then the host will simply reveal the other incorrect door. Note that there is nothing random about the reveal in this case.

This exercise is part of the course

Probability Puzzles in R

View Course

Exercise instructions

  • In the case when the initial choice was correct, use the sample function to randomly choose one of the other doors to reveal.
  • Otherwise, select the only remaining door to reveal.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

reveal_door <- function(doors, prize, initial_choice){
  if(prize == initial_choice){
    # Sample at random from the two remaining doors
    reveal <- sample(x = ___, size = 1)
  } else {
    
    # When the prize and initial choice are different, reveal the only remaining door 
    reveal <- ___
  }  
}
Edit and Run Code