# BinomialDistribution.R
# Calculating binomial probabilities is easy in R. The function 'binom.test' takes in
# three variables: (1) K, the number of successful outcomes, (2) N, the total number of trials,
# and (3) P, the probability of a successful outcome on any given trial.
#
# A fourth argument can be 'alternative = "less"', or 'alternative = "greater"', depending on
# whether you want Pr(xk)
#
# If you just want a binomial probability, that is, the probability of getting
# exactly k successful events out of N tries, you can use the function 'dbinom'
# where the three values go in the same order as 'binom.test'.
# Example: Given 10 flips of a fair 50/50 coin, what is the probability of
# getting exactly 6 heads?
dbinom(6,10,.5)
# Example: Given 10 flips of a fair 50/50 coin, what is the probability of obtaining 6 or more heads?
out <- binom.test(6,10,.5,
alternative = "greater")
out <- binom.test(5,10,.5,
alternative = "less")
# The result can be found in the field 'p.value':
print(out$p.value)
# Example: If you guess on a 20 question multiple choice test where each question has 5 possible
# answers, what is the probability of getting 4 or less correct?
out <- binom.test(4,20,1/5,
alternative = "less")
print(out$p.value)
# Example: If a basketball player has a 2 out 3 chance of making a free throw on any given try,
# and all tries are independent, what is the probability of making 7 or more out of 10?
out <- binom.test(7,10,2/3,
alternative = "greater")
print(out$p.value)
# This is the same as:
out <- binom.test(10-7,10,1-2/3,alternative = "less")
print(out$p.value)
# what do binomial distributions look like?
N <- 20
k <- seq(0,N) # 'sequence' of numbers counting from 0 to N
P <- .2
p <- dbinom(k,N,P)
barplot(p)
# To make the plot prettier, and to add labels:
barplot(height = p, # probabilities
names = k, # x axis values
col = 'blue', # color
xlab = 'k', # x label
ylab = 'Pr(k)', # y label
main = sprintf('N = %d',N), # title
space = 0) # spacing between bars