repeatable: Make a random number generator repeatable

Description Usage Arguments Value Note Examples

View source: R/utils.R

Description

Given a function that generates random data, returns a wrapped version of that function that always uses the same seed when called. The seed to use can be passed in explicitly if desired; otherwise, a random number is used.

Usage

1
repeatable(rngfunc, seed = stats::runif(1, 0, .Machine$integer.max))

Arguments

rngfunc

The function that is affected by the R session's seed.

seed

The seed to set every time the resulting function is called.

Value

A repeatable version of the function that was passed in.

Note

When called, the returned function attempts to preserve the R session's current seed by snapshotting and restoring base::.Random.seed().

Examples

1
2
3
4
5
6
rnormA <- repeatable(rnorm)
rnormB <- repeatable(rnorm)
rnormA(3)  # [1]  1.8285879 -0.7468041 -0.4639111
rnormA(3)  # [1]  1.8285879 -0.7468041 -0.4639111
rnormA(5)  # [1]  1.8285879 -0.7468041 -0.4639111 -1.6510126 -1.4686924
rnormB(5)  # [1] -0.7946034  0.2568374 -0.6567597  1.2451387 -0.8375699

Example output

[1]  2.09134796  0.09566928 -1.32201359
[1]  2.09134796  0.09566928 -1.32201359
[1]  2.09134796  0.09566928 -1.32201359 -2.16430637 -1.70157824
[1] -0.1173808  2.5484692 -0.1084237  0.9996421 -0.8172387

shiny documentation built on July 2, 2020, 12:43 a.m.