# Monty Hall Problem -- Solve using lapply() and a function # Chris Adolph # 10/8/2013 sims <- 10000 # Simulations run doors <- c(1,0,0) # The car (1) and the goats (0) # Faster: avoiding loops with lapply() result <- lapply(1:sims, function (x, doors) { pick <- sample(doors, 3, replace=FALSE); c(pick[1], max(pick[2:3])) }, doors) # Combine the list of results into a matrix result <- do.call(rbind, result) # Take the average of each column result <- apply(result, 2, mean) cat("Probability of a car from staying with 1st door", result[1],"\n") cat("Probability of a car from switching to 2nd door", result[2],"\n")