One way to generate uniformly distributed numbers in R is use the runif() function. runif is short for “random uniform”. R has other random number generating functions. For example rnorm generates random normal numbers.
runif() takes three arguments, thrst is n – number of numbers we want and min and max for generating numbers between the minimum number specified by min and a maximum number specified by max. In runif() function, the default values for the min and max are 0 and 1.
Let us see examples of generating uniform random numbers using runif().
library(tidyverse) theme_set(theme_bw(16))
runif() example 1
Generate 6 random numbers from uniform distribution between 0 and 1.
runif(n=6) [1] 0.20620689 0.88413284 0.86518893 0.86128241 0.62895272 0.05680614
runif() example 2
Generate 6 random numbers from uniform distribution between min=1 and max=10.
runif(n=6, min=1, max=10) [1] 5.949993 8.817129 2.038683 3.480969 6.253877 8.256257
Note runif() gives us float numbers not integers.
runif() example 3
To generate random integers with equal probability, i.e. from uniform distribution, we use runif() and then use floor/ceiling/round function to force them to integers in the range we want.
In the exampel below we use floor() function to the results from runif() to generate uniform random integers.
floor(runif(n=6, min=1, max=10)) [1] 4 4 5 3 2 7
See that if we run the same statement again , we get different set of random integers.
floor(runif(n=6, min=1, max=10)) [1] 9 1 2 5 5 7
Sometimes we want to reproduce the results, i.e. we want to generate the same random numbers. By setting a random seed, that is any integer number to set.seed() function, we can reproduce the same random numbers.
In the example below, we use set.seed(432) to generate random integers from uniform distribution that is reproducible.
set.seed(432) floor(runif(n=6, min=1, max=10)) [1] 3 1 9 2 7 9
By using the same seed, we can generate the same random numbers as we intended.
set.seed(432) floor(runif(n=6, min=1, max=10)) [1] 3 1 9 2 7 9
With uniform distribution, every number generated between an interval is equally likely. We can check that by similating large random numbers and looking at the distribuition. Here we generate 10000 random integers and see that every number has approximately equally likely.
set.seed(432) runif_large <- tibble(x = runif(10000, min = 1, max = 10 )) ggplot(ceiling(runif_large), aes(x = x)) + geom_histogram(binwidth=1, color = "white")+ geom_hline(yintercept = 1000, color="red")+ scale_x_continuous(breaks=scales::breaks_pretty(n=6))+ labs(title="Distribution of uniform random numbers") ggsave("uniform_distribution_example.png")