# R Functions Related to Binomial Distributions

To find the binomial probability of seeing exactly $x$ successes in $n$ trials, where the probability of success on any one trial is $p$. (i.e., ${}_n C_k p^x q^{n-x}$ where $q = 1-p$), we can use the following R function:

dbinom

Usage
dbinom(x, size = n, prob = p)

Example

To find the probability that one flips exactly 4 heads in 8 tosses of a fair coin, one could use the following:

> dbinom(4, size = 8, prob = 1/2)
[1] 0.2734375


If one needs to find the probability that the number of successes (with probability $p$) seen in $n$ trials is $x$ or less, one can use the following cumulative probability distribution function:

pbinom

Usage
pbinom(x, size = n, prob = p)

Examples

Suppose there are $12$ multiple choice questions in an English class quiz. Each question has five possible answers, and only one of them is correct. One way to find the probability of having four or less correct answers if a student attempts to answer every question at random, would be to do the following:

> dbinom(0, size=12, prob=0.2) +
+     dbinom(1, size=12, prob=1/5) +
+     dbinom(2, size=12, prob=1/5) +
+     dbinom(3, size=12, prob=1/5) +
+     dbinom(4, size=12, prob=1/5)
[1] 0.9274445

However, it will be far quicker to use the cumulative probability function for the binomial distribution:
> pbinom(4, size=12, prob=1/5)
[1] 0.9274445


If we instead wanted the probability of the student getting somewhere between $4$ and $8$ (inclusive) questions correct, we can use a difference of two cumulative probabilities, as the below illustrates:

> pbinom(8, size=12, prob=1/5) - pbinom(3, size=12, prob=1/5)
[1] 0.2053689


R also has a function that lets you simulate the outcome of a random variable $X$ that follows a binomial distribution:

rbinom

Usage
rbinom(x, size = n, prob = p)

Note: unlike the previous functions, here $x$ represents the number of realizations of your random variable you wish to produce.

Examples

The two examples below independently simulate $12$ trials where the probability of success is $1/5$ and return the number of successes seen. Note, there is a random element to this function, so it can (and does) return different values when you run it at different times.

> rbinom(1,size=12,prob=1/5)
[1] 2

> rbinom(1,size=12,prob=1/5)
[1] 4


If you want to run this experiment several times, you just alter the first parameter to the function. Below, we run the $12$ trials $6$ times, returning how many successes are seen each time.

> rbinom(6,size=12,prob=1/5)
[1] 3 4 5 2 2 2