Binomial distribution with R

This page is part of ‘My notes on R programming’ on my site: https://dataz4s.com/. It is a run through of the functions dbinom, pbinom, rbinom and qbinom functions in R:

Say that X is binomially distributed with n=15 trials and p=0.8 prob of success.

\[X\sim BIN(n=15; p=0.8)\]

dbinom

dbinom can be used to find values for the probability density function of X, f(x)

# P(X=9)
dbinom(x=9, size = 15, prob = 0.8)
## [1] 0.04299262

Multiple probailities:

# P(X=6) & P(X=7) & P(X=8) & P(X=9)
dbinom(x=6:9, size = 15, prob=0.8)
## [1] 0.0006717597 0.0034547643 0.0138190573 0.0429926226
# The probability of equal to or less than 9: P( <= 9)
sum( dbinom(x=0:9, size = 15, prob=0.8) )
## [1] 0.06105143

The above sum calculation can also be done with the pbinom function:

pbinom

pbinom function returns values for the probability distribution function of X, F(x)

# P( <= 9)
pbinom(q=9, size = 15, prob = 0.8, lower.tail = T)
## [1] 0.06105143

rbinom

The ‘rbinom’ function can be used to take a random sample from a binomial distribution. For example, if we have a production line and we produce 200 of ProductX per day. Defective products are returned for re-production. There is a 7% error rate. The number of ProductX of defectives per 5-days working week can be estimated like this:

rbinom(5,200,0.07)
## [1] 10 13 13 11 15
?rbinom
## starting httpd help server ... done

The rbinom can model Bernoulli trials by setting the ‘size’ (number of trials) equal to one. For example, for the outcome of 10 coin flips:

# 10 coin flips
rbinom(10, 1,.5)
##  [1] 0 0 0 0 1 0 1 0 0 0
#H or for 20 flips of 150 coins:
# 20 flips of 150 coins
rbinom(20,150,.5)
##  [1] 66 83 70 78 65 68 78 59 71 68 75 71 73 66 86 72 87 83 70 79

qbinom

The qbinom function calculates the inverse binomial distribution inverting the operation performed by pbinom. We provide the function specifying the percentile we want to be at or below and it will generate the number of successes associated with just that cumulative probability, for example:

qbinom(0.8,10,.5)
## [1] 6

View this content on my page: https://dataz4s.com/r-statistical-programming/binomial-distribution-in-r/