In this tutorial, we will learn how to simulate or generate random numbers from uniform distribution. In R, with the in-built function runif() we can generate uniform random numbers.
The basic usage of runif() function looks like this
runif(n, min = 0, max = 1),
where n refers to the number of random numbers we need and min/max is the interval of the uniform distribution we would like to sample from. By default, runif() generates random numbers between 0 and 1.
For example, here generate a single random number sampled from a U(0,1), uniform distribution ranging from 0 to 1.
runif(1) [1] 0.01725095
To reproduce the random numbers we can use set.seed() function with an integer as input. In this example, our seed is 42 and we generate a random number from U(0,1)
set.seed(42) runif(1, min=0, max=1) [1] 0.914806
And we can reproduce it
set.seed(42) runif(1, min=0, max=1) [1] 0.914806
To sample n uniform random numbers between 0 and 1, we provide the n as input argument to runif() function. Here we generate 5 random numbers from uniform distribution.
runif(5) [1] 0.9370754 0.2861395 0.8304476 0.6417455 0.5190959
To generate uniform random numbers from a different range, we specify min and max. In the example below we have set min=1 and max=10 to generate uniform random numbers from 1 to 10. And we generate 10 random numbers from interval 1 to 10.
runif(10, min=1, max=10) [1] 7.629295 2.211999 6.912931 7.345583 5.119676 7.472010 9.412050 [8] 3.298859 5.160635 9.460131
runif() function generates uniform real random numbers. Here we use round function to generate integers from uniform distribution.
round(runif(10, min=1, max=10)) [1] 10 2 5 6 9 2 10 10 2 6