Binomial Probabilities


On your USB drive, create a new directory, copy model.R to that directory, rename the file in the new directory, double click on the file to open Rstudio. Then copy all of the text below the line and paste it into your Rstudio editor pane.
# Some examples of binominal probabilities
#
#  First, introduce pbinom().

#  What is the probability of getting 8 or fewer 
#  successes in 23 trials, if the probability of success
#  is 0.42?
pbinom( 8, 23, 0.42 )
#
#  What is the probability of getting 7 or fewer 
#  successes in 23 trials, if the probability of success
#  is 0.42?
pbinom( 7, 23, 0.42 )
#
#  Then, let us take care of getting an exact 
#  probability.
#
#  What is the probability of getting exactly 8
#  successes in 23 trials if the probability of
#  success is 0.42?
#
pbinom( 8, 23, 0.42) - pbinom( 7, 23, 0.42)
#
#  Alternatively, we do have a special function, 
#  pbinomeq() that will find that same value
#  but we need to load it into our environment.
#
source("../pbinomeq.R")
pbinomeq( 8, 23, 0.42)

#
# Then we start to look at stranger questions.
#
#  what is the probability of getting anything
#  other than 8 successes out of 23 trials when
#  the probability of success is 0.42?
#
1 - pbinomeq( 8, 23, 0.42)
#
#  What is the probability of getting more than
#  8 successes out of 23 trials witen the 
#  probability of success is 0.42?
#
1 - pbinom( 8, 23, 0.42 )
#
#  We should note that R has a special parameter
#  that is often used to change the direction of
#  our view of the probabilty distribution.  That
#  parameter is lower.tail, and we can demonstrate
#  it here.
#
#  The probability of getting 8 or fewer successes
#  for our case was
pbinom( 8, 23, 0.42 )
#  The probability of getting more than 8 is
1 - pbinom( 8, 23, 0.42 )
#  but we could have done that by
pbinom( 8, 23, 0.42, lower.tail=FALSE)
# 
#   Note that pbinom( 8, 23, 0.42 ) gave us
#      8 or less
#  but that pbinom( 8, 23, 0.42, lower.tail=FALSE)
#      gives us more than 8,
#   specifically, not "8 or more'!
#
#  What is the probability of getting fewer
#  than 8 successes in 23 trials with the 
# probability of success = 0.42?
#
#  "fewer than 8" is the same as 
#  # 7 of less" so
pbinom( 7, 23, 0.42)
#
#  We could have done this same problem by saying 
#  "fewer than 8" is the same as the complement
#  of "more than 7"
1 - pbinom( 7, 23, 0.42, lower.tail=FALSE)
#
#  What is the probability of getting between
#  10 and 14 successes out of 23 trials,
#  including 10 and 14, with
#  the probability of a success = 0.42?
#
# pbinom( 14, 23, 0.42) is the probabilty 
# of getting 14 or fewer. And, pbinom(9, 23, 0.42)
# of getting 9 or fewer, so
pbinom( 14, 23, 0.42) - pbinom( 9, 23, 0.42)
# is our answer.
#
#  What is the probability of getting fewer than
#  6 or more than 14 successes out of 23 trials 
#  when the probability of success is 0.42?
pbinom( 5, 23, 0.42) + 
       pbinom( 14, 23, 0.42, lower.tail=FALSE)