Question

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.

Was it helpful?

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>

OTHER TIPS

There is also the SoDa package (and manual [PDF]) which allows you to wrap other operations and recover the starting and ending seed. It's just a wrapper around set.seed() but you can check for yourself (e.g. in unit tests) more easily.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top