How to generate random values from a distribution (in R)
Task
There are many famous continuous probability distributions, such as the normal and exponential distributions. How can we get access to them in software, to generate random values from a chosen distribution?
Related tasks:
- How to compute probabilities from a distribution
- How to plot continuous probability distributions
- How to plot discrete probability distributions
Solution
Because R is designed for use in statistics, it comes with many probability distributions built in. A list of them is online here.
Regardless of whether the distribution is discrete or continuous,
prefix the name of the distribution with r
, which stands for “random values.”
Here are two examples.
Using a normal distribution:
1
2
# 20 random values from the normal distribution with μ=10 and σ=5
rnorm( 20, mean=10, sd=5 )
1
2
3
[1] 8.281648 9.853892 16.533054 15.195100 10.301387 8.169758 -2.927952
[8] 9.463419 6.168776 15.666091 13.382661 4.286710 11.340385 6.448717
[15] 9.148462 11.744665 8.869667 13.177116 6.309141 8.888176
Using a uniform distribution:
1
2
# 20 random values from the uniform distribution on the interval [50,60]
runif( 20, min=50, max=60 )
1
2
3
[1] 59.59391 59.85593 54.76225 57.33802 54.03049 52.52659 51.66029 58.05590
[9] 56.11249 53.00606 58.47839 52.03311 54.31438 57.61727 53.04272 55.41182
[17] 51.47592 59.49853 55.94943 58.30232
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)