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 = NULL,
.rng_normal_kind = NULL,
.rng_sample_kind = NULL
)
local_seed(
seed,
.local_envir = parent.frame(),
.rng_kind = NULL,
.rng_normal_kind = NULL,
.rng_sample_kind = NULL
)
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, .rng_normal_kind, .rng_sample_kind
[character(1)]
Kind of RNG to use. Passed as thekind
,normal.kind
, andsample.kind
arguments ofRNGkind()
.- .local_envir
[environment]
The environment to use for scoping.
See also
withr
for examples
Examples
# Same random values:
with_preserve_seed(runif(5))
#> [1] 0.60122029 0.71432200 0.21251776 0.57071921 0.03314651
with_preserve_seed(runif(5))
#> [1] 0.60122029 0.71432200 0.21251776 0.57071921 0.03314651
# 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.6524811 0.0481857 0.4207581 0.0576367 0.4022035
with_seed(seed, runif(5))
#> [1] 0.6524811 0.0481857 0.4207581 0.0576367 0.4022035
with_seed(seed <- sample.int(.Machine$integer.max, 1L), runif(5))
#> [1] 0.5603091 0.3532899 0.7418730 0.9625902 0.2340096