Debian Codegraph @

R/rng.R

raw
1 #' RNG version
2 #'
3 #' Change the RNG version and restore it afterwards.
4 #'
5 #' `with_rng_version()` runs the code with the specified RNG version and
6 #' resets it afterwards.
7 #'
8 #' `local_rng_version()` changes the RNG version for the caller
9 #' execution environment.
10 #'
11 #' @template with
12 #' @param version `[character(1)]` an R version number, e.g.
13 #' `"3.5.0"`, to switch to the RNG this version of R uses.
14 #' See [RNGversion()].
15 #'
16 #' @seealso [RNGversion()], [RNGkind()], [with_seed()].
17 #' @export
18 #' @examples
19 #' RNGkind()
20 #' with_rng_version("3.0.0", RNGkind())
21 #' with_rng_version("1.6.0", RNGkind())
22 #'
23 #' with_rng_version("3.0.0",
24 #' with_seed(42, sample(1:100, 3)))
25 #'
26 #' with_rng_version("1.6.0",
27 #' with_seed(42, sample(1:100, 3)))
28 #'
29 #' RNGkind()
30 #'
31 with_rng_version <- function(version, code) {
32 old <- RNGkind()
33 on.exit(restore_rng_kind(old), add = TRUE)
34 suppressWarnings(RNGversion(version))
35 code
36 }
37
38 #' @rdname with_rng_version
39 #' @param .local_envir The environment to apply the change to.
40 #' @export
41 #' @examples
42 #' fun1 <- function() {
43 #' local_rng_version("3.0.0")
44 #' with_seed(42, sample(1:100, 3))
45 #' }
46 #'
47 #' fun2 <- function() {
48 #' local_rng_version("1.6.0")
49 #' with_seed(42, sample(1:100, 3))
50 #' }
51 #'
52 #' RNGkind()
53 #' fun1()
54 #' fun2()
55 #' RNGkind()
56 local_rng_version <- function(version, .local_envir = parent.frame()) {
57 old <- RNGkind()
58 defer(restore_rng_kind(old), envir = .local_envir)
59 suppressWarnings(RNGversion(version))
60 old
61 }
62
63 restore_rng_kind <- function(kind) {
64 # Silence static analysis linting about `RNGkind()` signature on old
65 # R versions
66 RNGkind <- get("RNGkind")
67
68 RNGkind(kind[[1]], normal.kind = kind[[2]])
69
70 # Within a `local_rng_version("3.5.0")`, we restore to `"Rounding"`,
71 # which causes a warning. See https://github.com/r-lib/withr/issues/167
72 sample_kind <- kind[[3]]
73 if (identical(sample_kind, "Rounding")) {
74 suppressWarnings(
75 RNGkind(sample.kind = sample_kind)
76 )
77 } else {
78 RNGkind(sample.kind = sample_kind)
79 }
80
81 NULL
82 }