Categories
BLOG

r get seed

Saving the state of the random number generator

Problem

You want to save and restore the state of the random number generator

Solution

Save .Random.seed to another variable and then later restore that value to .Random.seed .

If no random number generator has been used in your R session, the variable .Random.seed will not exist. If you cannot be certain that an RNG has been used before attempting to save, the seed, you should check for it before saving and restoring:

Saving and restoring the state of the RNG in functions

If you attempt to restore the state of the random number generator within a function by using .Random.seed , it will not work, because this operation changes a local variable named .Random.seed , instead of the variable in the global envrionment.

Here are two examples. What these functions are supposed to do is generate some random numbers, while leaving the state of the RNG unchanged.

This site is powered by knitr and Jekyll. If you find any errors, please email [email protected]