File: with_stealth_rng.R

package info (click to toggle)
r-cran-future.batchtools 0.12.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 528 kB
  • sloc: sh: 82; makefile: 2
file content (22 lines) | stat: -rw-r--r-- 732 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
## Evaluates an R expression while preventing any changes to .Random.seed
with_stealth_rng <- function(expr, substitute = TRUE, envir = parent.frame(), ...) {
  if (substitute) expr <- substitute(expr)

  ## Record the original RNG state
  oseed <- .GlobalEnv$.Random.seed
  on.exit({
    if (is.null(oseed)) {
      if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
        rm(list = ".Random.seed", envir = .GlobalEnv, inherits = FALSE)
      }	
    } else {
      .GlobalEnv$.Random.seed <- oseed
    }
  })

  ## Evaluate the R expression with "random" RNG state
  if (!is.null(oseed)) {
    rm(list = ".Random.seed", envir = .GlobalEnv, inherits = FALSE)
  }
  eval(expr, envir = envir, enclos = baseenv())
}