Generating random numbers is a fundamental task in many kinds of programming. I decided to investigate how to generate random integers using the R language.
I came up with three techniques. My conclusion is that using the built-in sample() function is the easiest.
Suppose you want to generate random integers between 1 and 4 inclusive. Using the built-in sample() function:
rn = sample(1:4, 1)
Here the 1 argument means one value. The sample() function, like many R functions has many optional parameters that give many different behaviors.
Using the built-in runif() function:
rn = floor(runif(1, min=1, max=5))
The name “runif” stands for “random – uniform”. The runif() function here returns a value between 1.0 and 5.0 exclusive (think 1.00001 to 4.99999), The floor() function returns the integer part, 1 to 4.
Using a pattern that’s common in other programming languages:
lo = as.integer(1) hi = as.integer(5) rn = as.integer((hi-lo) * runif(1) + lo)
In this version, runif() is using default values of min = 0.0 and max = 1.0 which corresponds to how random number generators work in many other languages.
Anyway, using the sample() function is simple and easy and the other techniques would only be used in unusual situations.