with_seed() runs code with a specific random seed and resets it afterwards.

with_preserve_seed() runs code with the current random seed and resets it afterwards.

with_seed(seed, code)

with_preserve_seed(code)

Arguments

seed

[integer(1)]
The random seed to use to evaluate the code.

code

[any]
Code to execute in the temporary environment

Value

[any]
The results of the evaluation of the code argument.

See also

withr for examples

Examples

# Same random values: with_preserve_seed(runif(5))
#> [1] 0.87460066 0.17494063 0.03424133 0.32038573 0.40232824
with_preserve_seed(runif(5))
#> [1] 0.87460066 0.17494063 0.03424133 0.32038573 0.40232824
# Use a pseudorandom value as seed to advance the RNG and pick a different # value for the next call: with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5))
#> [1] 0.3469616 0.8300169 0.6851683 0.6277089 0.9512036
with_seed(seed, runif(5))
#> [1] 0.3469616 0.8300169 0.6851683 0.6277089 0.9512036
with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5))
#> [1] 0.6623930 0.3836579 0.8633871 0.9146275 0.6936791