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.7561099 0.8544975 0.7070987 0.5274851 0.4269771
with_preserve_seed(runif(5))
#> [1] 0.7561099 0.8544975 0.7070987 0.5274851 0.4269771
# 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.4458329 0.7415593 0.6138094 0.8396217 0.4743131
with_seed(seed, runif(5))
#> [1] 0.4458329 0.7415593 0.6138094 0.8396217 0.4743131
with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5))
#> [1] 0.71317290 0.02839187 0.71035578 0.25841644 0.40783404