Suppose 65% SML201 students like World Coffee better than Hoagie Haven. We selected a random sample of 20 SML201 students, and asked them which they prefer. What is the probability that more than 18 students said “World Coffee”? Write R code to compute the actual probability.
Hint:
pbinom
, just like we did in class.This is like asking about the probability of a coin’s coming up heads 18 times or more out of 20 when the probability of the coin’s coming up heads is 65%:
1 - pbinom(q = 18, size = 20, prob = 0.65)
## [1] 0.00213312
The answer is 0.2%.
Here’s another way to compute the answer:
sum(dbinom(x = c(19, 20), size = 20, prob = 0.65))
## [1] 0.00213312
In class, we saw several ways to compute the cumulative probability for the binomial distribution: we used pbinom
; we summed up the outputs of dbinom
; we also generated a large sample using rbinom
, and then computed the proportion of the generated numbers that was under a certain threshold.
Write a function named MyPbinom1
, which works just like pbinom
. You may use dbinom
but not rbinom
in the function you write.
MyPbinom1 <- function(q, size, prob){
return(sum(dbinom(x = 0:q, size = size, prob = prob )))
}
MyPbinom1(q = 2, size = 10, prob = 0.45)
## [1] 0.09955965
pbinom(q = 2, size = 10, prob = 0.45)
## [1] 0.09955965
Write a function named MyPbinom2
, which works just like pbinom
. You may use rbinom
but not dbinom
in the function you write.
MyPbinom2 <- function(q, size, prob){
sample <- rbinom(n = 10000000, size = size, prob = prob)
return(mean(sample <= q))
}
MyPbinom2(q = 2, size = 10, prob = 0.45)
## [1] 0.0994306
pbinom(q = 2, size = 10, prob = 0.45)
## [1] 0.09955965