0

I am making a Monty Hall problem simulation and trying to get the probability of confidence interval in R.

# set the door 
door <- c(1,2,3) 

# count success 
count <- 0

MontyHallchallenge3 <- function(a){
    for (i in 1:a) {
      car <- sample(door, 1)
      choice <- sample(door, 1)
      if(car == choice){
        host <- sample(setdiff(door, car), 1)
      }else{
        host <- setdiff(door, c(choice, car))
      }
      secondchoice <- setdiff(door, c(host, choice))
      if(secondchoice == car){
        count <- count + 1
      }
    }
    p = count/a
  return(mean(p))
}

b = c(2,10,100,1000)
mapply(MontyHallchallenge3, a = b)

a is a sample size and pass it to the function as an argument. I was given a = 2,10,100,1000 and I am supposed to create the each confidence interval. Right now, it iterate only once and get these.

> mapply(MontyHallchallenge3, a = b)
[1] 0.500 0.800 0.660 0.642

I would like to iterate 1000 times for each sample to get the confidence interval. Is there any way to set the number of iteration in mapply()?

macaroni
  • 25
  • 1
  • 4

2 Answers2

0

You can use replicate to iterate 1000 times for each value in b and take mean of it.

b = c(2,10,100,1000)
sapply(b, function(x) mean(replicate(1000, MontyHallchallenge3(x))))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
-1

We can use replicate with lapply

b <- c(2, 10, 100, 1000)
lapply(b, function(x) mean(replicate(1000, MontyHallchallenge3(x))))
akrun
  • 874,273
  • 37
  • 540
  • 662