# Toss a fair coin 10 times coinToss <- sample(c("H", "T"), 10, replace = TRUE) coinToss # Estimate the probability that you observe Heads for the # third time on the 10th toss. sum(coinToss == "H") sum(coinToss == "H") == 3 sum(coinToss[1:9] == "H") == 2 sum(coinToss == "H") == 3 & sum(coinToss[1:9] == "H") == 2 event <- replicate(10000, { coinToss <- sample(c("H", "T"), 10, replace = TRUE) (sum(coinToss == "H") == 3 & coinToss[10] == "H") }) mean(event) # Roll a pair of dice 1000 times. # What is the probability that the value of the second die # is greater than the value of the first die? help(sample) n <- 1000; n x <- sample(1:6, size = n, replace = TRUE) head(x) y <- sample(1:6, size = n, replace = TRUE) head(y) z <- (x < y) head(z) mean(z) # answer 15/36 15/36 # Now replicate the simulation of the 1000 rolls, 1000 times. B <- 1000; B # number of replications n <- 1000; n # number of rolls of the pair of dice z <- replicate(B, { x <- sample(1:6, size = n, replace = TRUE) y <- sample(1:6, size = n, replace = TRUE) z <- (x < y) mean(z) }) head(z) hist(z)