Skip to content
Prev 27613 / 63424 Next

Best way to reset random seed when using set.seed() in a function?

On Feb 13, 2008 9:32 AM, Prof Brian Ripley <ripley at stats.ox.ac.uk> wrote:
Thank you, and thanks for the pointer.  I had another question if
'.Random.seed' can end up somewhere else than in the global
environment, but 'R Internals' clearly states that .Random.seed
belongs in the global environment.  My short example was not explicit
about that (and hence to bullet proof).  Here is an update version:

foo <- function(n) {
  # Store old random state
  if (!exists(".Random.seed", mode="numeric", envir=globalenv()))
    sample(NA);
  oldSeed <- get(".Random.seed", mode="numeric", envir=globalenv());

  # Fixed seed to get reproducible samples here
  set.seed(0xbeef);
  x <- sample(5);

  # Proof of concept: 'x' should be the same all the time
  stopifnot(identical( x, as.integer(c(4,2,5,1,3)) ));

  # Reset random seed to old state
  assign(".Random.seed", oldSeed, envir=globalenv());

  # Continue as nothing happened
  sample(n);
}

Cheers

Henrik