Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

with_seed

Random seed


Description

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.

Usage

with_seed(
  seed,
  code,
  .rng_kind = "default",
  .rng_normal_kind = "default",
  .rng_sample_kind = "default"
)

local_seed(
  seed,
  .local_envir = parent.frame(),
  .rng_kind = "default",
  .rng_normal_kind = "default",
  .rng_sample_kind = "default"
)

with_preserve_seed(code)

local_preserve_seed(.local_envir = parent.frame())

Arguments

seed

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

code

[any]
Code to execute in the temporary environment

.rng_kind

[character(1)]
Kind of (uniform) RNG to use.

.rng_normal_kind

[character(1)]
Kind of normal RNG to use.

.rng_sample_kind

[character(1)]
Kind of RNG to use for sampling.

.local_envir

[environment]
The environment to use for scoping.

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))
with_preserve_seed(runif(5))

# 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))
with_seed(seed, runif(5))
with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5))

withr

Run Code 'With' Temporarily Modified Global State

v2.4.2
MIT + file LICENSE
Authors
Jim Hester [aut, cre], Kirill Müller [aut], Kevin Ushey [aut], Hadley Wickham [aut], Winston Chang [aut], Jennifer Bryan [ctb], Richard Cotton [ctb], RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.