Simulation Programming in R
One of the most common uses of R is simulation. Let’s see what kinds of tools R has available for this application.
Built-In Random Variate Generators
As mentioned, R has functions to generate variates from a number of different distributions. For example, rbinom()
generates binomial or Bernoulli random variates.[3]
Let’s say we want to find the probability of getting at least four heads out of five tosses of a coin (easy to find analytically, but a handy example). Here’s how we can do this:
> x <- rbinom(100000,5,0.5) > mean(x >= 4) [1] 0.18829
First, we generate 100,000 variates from a binomial distribution with five trials and a success probability of 0.5. We then determine which of them has a value 4 or 5, resulting ...
Get The Art of R Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.