Binomial Random number Generation in R
We will learn here how to generate Bernoulli or Binomial distribution in R with the example of a flip of a coin. This tutorial is based on how to generate random numbers according to different statistical distributions in R. Our focus is on binomial random number generation in R.
We know that in Bernoulli distribution, either something will happen or not such as coin flip has to outcomes head or tail (either head will occur or head will not occur i.e. tail will occur). For an unbiased coin, there will be a 50% chance that the head or tail will occur in the long run. To generate a random number that is binomial in R, use rbinom(n, size, prob) command.
rbinom(n, size, prob) #command has three parameters, namey
where
‘n’ is the number of observations
‘size’ is the number of trials (it may be zero or more)
‘prob’ is the probability of success on each trial for example 1/2
Some Examples
- One coin is tossed 10 times with probability of success=0.5
coin will be fair (unbiased coin as p=1/2)rbinom(n=10, size=1, prob=1/2)
OUTPUT: 1 1 0 0 1 1 1 1 0 1 - Two coins are tossed 10 times with probability of success=0.5
-
rbinom(n=10, size=2, prob=1/2)
OUTPUT: 2 1 2 1 2 0 1 0 0 1 - One coin is tossed one hundred thousand times with probability of success=0.5
rbinom(n=100,000, size=1, prob=1/2)
- store simulation results in $x$ vector
x<- rbinom(n=100,000, size=5, prob=1/2)
count 1’s in x vectorsum(x)
find the frequency distributiontable(x)
creates a frequency distribution table with frequencyt = (table(x)/n *100)}
plot frequency distribution tableplot(table(x),ylab = "Probability",main = "size=5,prob=0.5")
View Video tutorial on rbinom command