[1] 1 2 3 4 5 6 7 8 9 10
[1] 3
Problem: 10 people are at a party, and all of them are wearing hats. They each place their hat in a pile; when they leave, they choose a hat at random. What is the probability at least one person selected the correct hat?
Question: Work with your neighbor to discuss the following question:
hats is a vector, containing the numbers 1 to 10 [1] 1 2 3 4 5 6 7 8 9 10
[1] 4 7 1 3 8 10 9 2 5 6
sample function creates a random sample from a vectorA for loop repeats code many times:
A for loop repeats code many times:
A for loop repeats code many times:
nsim <- 10000 # number of simulations
hats <- 1:10
results <- rep(NA, nsim) # vector to store results
for(i in 1:nsim){
randomized_hats <- sample(hats, size = 10, replace = FALSE)
results[i] <- sum(hats == randomized_hats) > 0
}
mean(results)[1] 0.6231
Without magic numbers:
nsim <- 10000 # number of simulations
n_people <- 10 # number of people
hats <- 1:n_people
results <- rep(NA, nsim) # vector to store results
for(i in 1:nsim){
randomized_hats <- sample(hats,
size = n_people,
replace = FALSE)
results[i] <- sum(hats ==
randomized_hats) > 0
}
mean(results)[1] 0.6316
set.seed(3) # set a seed for reproducibility
n_people <- 10 # number of people at the party
hats <- 1:n_people # numbered hats
nsim <- 10000 # number of simulations
results <- rep(NA, nsim) # vector to store the results
for(i in 1:nsim){
# hats are randomly assigned to each person
randomized_hats <- sample(hats, n_people, replace = F)
# did at least one person get their hat back?
results[i] <- sum(randomized_hats == hats) > 0
}
mean(results)set.seed(3) # set a seed for reproducibility
n_people <- 10 # number of people at the party
hats <- 1:n_people # numbered hats
nsim <- 10000 # number of simulations
results <- rep(NA, nsim) # vector to store the results
for(i in 1:nsim){
# hats are randomly assigned to each person
randomized_hats <- sample(hats, n_people, replace = F)
# did at least one person get their hat back?
results[i] <- sum(randomized_hats == hats) > 0
}
mean(results)How could we do this with map instead?
Will this do what I want?
set.seed(3)
nsim <- 20
n_people <- 10
hat_match <- function(n){
hats <- 1:n
randomized_hats <- sample(hats, n, replace = F)
sum(randomized_hats == hats) > 0
}
map_lgl(1:nsim, function(i) hat_match(n_people)) [1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE
[13] TRUE TRUE TRUE FALSE TRUE FALSE FALSE TRUE
https://sta279-f25.github.io/class_activities/ca_12.html