In this lesson we learn about generating “random” numbers in R.
Remember: In this lesson, all R code is below the R Source button, while the output is hidden. To see it you will need to click on the green “R Output” button. At the bottom of the page, you will find a bar which allows you to change the theme of the webpage (changing colors and format) so it can easily adapt to your system and preferences. There you also find “Code highlighting” which changes how R code is displayed to you, and Toggle R code and Figures.
The random word is between quotes above because R - or any software - cannot really generate truly random numbers. It gets really close though. This is because softwares use an algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers. This is termed a pseudorandom number generator, which is not truly random, because it is completely determined by a relatively small set of initial values, called the seed.
Below we will sample from several vectors, and emulate tossing a coin, rolling a die, playing the lottery, etc.
# Toss a coin
sample(0:1, 1)
# Toss 10 coins
sample(0:1, 10, replace = T)
# Roll a die
sample(1:6, 1)
# Roll 10 dice
sample(1:6, 10, replace = T)
# Roll a Icosahedron (20 sides die)
sample(1:20, 10, replace = T)
# Lottery
sample(1:49, 6, replace = F)
# Pick a card, any card...
sample(1:54, 6, replace = F)
# That is a bit clunky, let's try something more advanced
sample(paste(rep(c(1:10, "Jacks", "Queen", "King"), 4), rep(c("of Hearts", "of Diamonds",
"of Spades", "of Clubs"), 13), sep = " "), 1)
In computational statistics, and in R, random numbers are described by a distributions, which is a function specifying the probability that a random number is within some range. If the random number is continuous this is called “probability density function”, if the random number is discrete then the term is “probability mass function”.
If you want to learn more about Probability density functions, you can run the code below in your RStudio, which will produce a Shiny App displaying the probability density functions for the Normal, Poisson and Beta distributions. Here’s the link if you want the raw App
install.packages("shiny", dependencies = TRUE)
library(shiny)
runGist("00641dba8784bb81bd10")
How to choose a random number in R? As a language for statistical analysis, R has a comprehensive library of functions for generating random numbers from various statistical distributions.
Distribution | R Function |
---|---|
Uniform | runif |
Normal | rnorm |
Student’s t | rt |
F | rf |
chi-squared | rchisq |
Exponential | rexp |
Log normal | rlnorm |
Beta | rbeta |
Binomial | rbinom |
Negative Binomial | rnbinom |
Poisson | rpois |
Gamma | rgamma |
Weibull | rweibull |
Cauchy | rcauchy |
Multinomial | rmultinom |
Geometric | rgeom |
?Distributions | full list |
The Uniform Distribution
If you want to generate a decimal number where any value (including fractional values) between the stated minimum and maximum is equally likely, the runif() function is what you are looking for.This function generates values from the Uniform distribution. Here’s how to generate one random number between 0 and 1:
runif(1, min = 0, max = 1)
Of course, when you run this, you’ll get a different number, but it will definitely be between 0 and 1. You won’t get the values 0 or 1 exactly, either.
If you want to generate multiple random values, you can generate several values at once by specifying the number of values you want as the first argument to runif. Here’s how to generate 10 values between 0 and 1.
runif(10, 0, 1)
The Normal Distribution
To generate numbers from a normal distribution, use rnorm().
# By default the mean is 0 and the standard deviation is 1
rnorm(1)
rnorm(5)
mean(rnorm(100))
# Define mean and standard deviation
rnorm(1, mean = 5, sd = 1)
rnorm(5, mean = 5, sd = 3)
rnorm(100, mean = 10, sd = 10)
# Check that the distribution looks right, make a histogram of the numbers
hist(rnorm(100, mean = 10, sd = 10), breaks = 10)
The Poisson Distribution
To generate numbers from a poisson distribution, use rpois(). The Poisson distribution is popular for modeling the number of times an event occurs in an interval of time or space. The Poisson distribution may be useful to model events such as:
In probability theory, a Poisson process is a stochastic process that counts the number of independent events in a given time interval. The Poisson distribution can also be used for the number of events in other specified intervals such as distance, area or volume.
#
rpois(10, 1)
rpois(10, 4)
# In the poisson ditribution mean and variance are the same: lambda
rpois(10, lambda = 1)
rpois(10, lambda = 5)
# Check that the distribution looks right, make a histogram of the numbers
hist(rpois(1000, lambda = 1), breaks = 5)
Let’s say I have a categorical variable which can take the values A, B, C and D. How can I generate 10000 random data points and control for the frequency of each? For example: A = 10% B = 20% C = 65% D = 5%. Any ideas how to do this? Don’t fret if you have no ideas. I didn’t when I first tried to solve it. But it helped me a great deal to practice the skills I learned and how they can be useful.