withSeed.Rd
Evaluate an R expression with a temporarily set random set.
withSeed(expr, seed, ..., substitute=TRUE, envir=parent.frame())
The R expression to be evaluated.
Arguments passed to set.seed
().
If TRUE
, argument expr
is
substitute()
:ed, otherwise not.
The environment
in which the expression should be evaluated.
Returns the results of the expression evaluated.
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.
Internally, set.seed
() is used to set the random seed.
# Generate a random number
y0 <- runif(1)
print(y0)
#> [1] 0.5637715
# 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
}
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
#> [1] 0.9899366
# Generate a random number
y <- runif(1)
print(y)
#> [1] 0.1299701