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

Description Usage Arguments Details Value Author(s) See Also Examples

Description

Evaluate an R expression with a temporarily set random set.

Usage

1
withSeed(expr, seed, ..., substitute=TRUE, envir=parent.frame())

Arguments

expr

The R expression to be evaluated.

seed, ...

Arguments passed to set.seed().

substitute

If TRUE, argument expr is substitute():ed, otherwise not.

envir

The environment in which the expression should be 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.

Value

Returns the results of the expression evaluated.

Author(s)

Henrik Bengtsson

See Also

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

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 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)

Example output

Loading required package: R.oo
Loading required package: R.methodsS3
R.methodsS3 v1.8.1 (2020-08-26 16:20:06 UTC) successfully loaded. See ?R.methodsS3 for help.
R.oo v1.24.0 (2020-08-26 16:11:58 UTC) successfully loaded. See ?R.oo for help.

Attaching package:R.ooThe following object is masked frompackage:R.methodsS3:

    throw

The following objects are masked frompackage:methods:

    getClasses, getMethods

The following objects are masked frompackage:base:

    attach, detach, load, save

R.utils v2.10.1 (2020-08-26 22:50:31 UTC) successfully loaded. See ?R.utils for help.

Attaching package:R.utilsThe following object is masked frompackage:utils:

    timestamp

The following objects are masked frompackage:base:

    cat, commandArgs, getOption, inherits, isOpen, nullfile, parse,
    warnings

[1] 0.9008901
[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
[1] 0.9932795

R.utils documentation built on Sept. 26, 2021, 9:07 a.m.