Monte Carlo 在 R 中模拟 Monty Hall 问题不起作用?

Monte Carlo simulation in R for Monty Hall problem not working?

我正在用 R 编写一个函数来对 Monty Hall 问题执行 Monte Carlo 模拟。当门没有打开时,该功能正常工作 switch == FALSE,但是当我调用 mean(replicate(10000, monty_hall(switch = TRUE))) 时,预期的答案大约是 0.66 但我实际上绕过了 0.25.

函数代码如下:

monty_hall = function(switch = logical()){
    doors <- c(1,2,3)
    names(doors) <- rep(c("goat", "car"), c(2,1))
    prize_door <- doors[3]

    guess <- sample(doors, 1)
    revealed_door <- sample(doors[!doors %in% c(guess, prize_door)],1)
    if(switch){
        switched_door <- sample(doors[!doors %in% c(guess, revealed_door)],1)
        prize_door == switched_door
    } else {
        prize_door == guess
        }
}

我应该做哪些更改才能获得正确的输出,即 0.66 左右?

只需将门矢量更改为字符

monty_hall = function(switch = logical()){
   doors <- c("1","2","3")
   names(doors) <- rep(c("goat", "car"), c(2,1))
   prize_door <- doors[3]

   guess <- sample(doors, 1)
   revealed_door <- sample(doors[!doors %in% c(guess, prize_door)],1)
   if(switch){
      switched_door <- sample(doors[!doors %in% c(guess, revealed_door)],1)
      prize_door == switched_door
   } else {
      prize_door == guess
   }
}

假设这个人选择了1号门,奖品在2号门,那么剩下要揭晓的就是3号门。

您将拥有 revealed_door <- sample(3,1),但这并没有像您期望的那样工作,这变成了 revealed_door <- sample(c(1,2,3),1)

从函数文档中,只需键入 ?sample

If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x. Note that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as sample(x)

我认为最简单的解决方法是更改​​为字符,但如果您必须使用数值,只需检查向量的长度和 return 如果它是 1 的值,否则做一个示例