Search code examples
rrandomprng

Deterministic pseudorandom number generation in R


I need to generate a vector of "random" numbers, except that they need to be fully deterministic. The distribution from which the numbers come is not so important. What is a simple way to do this in R?

The reason for not using something like runif is that it returns a different sequence every time it is called.

The reason for not generating one sequence (with runif) and reusing it is that the calls are made on different machines. I could hardcode the sequence into a script, but the length of the sequence needed is unknown at design-time, so a pseudorandom sequence based on some hardcoded seed is preferable.


Solution

  • Are you aware of the set.seed() command?

    R> set.seed(42); runif(3)           
    [1] 0.914806 0.937075 0.286140
    R> set.seed(42); runif(3)            # same seed, same numbers
    [1] 0.914806 0.937075 0.286140
    R> set.seed(12345); runif(3)         # different seed, different numbers
    [1] 0.720904 0.875773 0.760982
    R>