R.utils (version 2.0.1)

withSeed: Evaluate an R expression with a temporarily set random set

Description

Evaluate an R expression with a temporarily set random set.

Usage

withSeed(expr, seed, ..., envir=parent.frame())

Arguments

expr
The R expression to be evaluated.
seed, ...
Arguments passed to set.seed().
envir
The environment in which the expression should be evaluated.

Value

  • Returns the results of the expression evaluated.

Details

Upon exit (also on errors), this function will restore .Random.seed in the global environment to the value it had upon entry. If it did not exist, it will be removed.

See Also

Internally, set.seed() is used to set the random seet.

Examples

Run this code
# Generate a random number
y0 <- runif(1)
print(y0)

# Generate a random number using the same seed over and over
yp <- NULL
for (ii in 1:10) {
  y <- withSeed({
    runif(1)
  }, seed=0x42)
  print(y)
  # Assert identical
  if (!is.null(yp)) stopifnot(identical(y, yp))
  yp <- y
}

# Generate a random number
y <- runif(1)
print(y)

Run the code above in your browser using DataCamp Workspace