RNGseed
directly gets/sets the current RNG seed
.Random.seed
. It can typically be used to backup
and restore the RNG state on exit of functions, enabling
local RNG changes.
RNGrecovery
recovers from a broken state of
.Random.seed
, and reset the RNG settings to
defaults.
RNGseed(seed) RNGrecovery()
invisibly the current RNG seed when called with no
arguments, or the -- old -- value of the seed before
changing it to seed
.
# get current seed
RNGseed()
# directly set seed
old <- RNGseed(c(401L, 1L, 1L))
# show old/new seed description
showRNG(old)
## # RNG kind: Mersenne-Twister / Inversion
## # RNG state: 403L, 1L, ..., -958897553L [c1718659a7a9800618c4379c622f5c5b]
showRNG()
## # RNG kind: Marsaglia-Multicarry / Inversion
## # RNG state: 401L, 1L, 1L
# set bad seed
RNGseed(2:3)
try( showRNG() )
# recover from bad state
RNGrecovery()
showRNG()
## # RNG kind: Mersenne-Twister / Inversion
## # RNG state: 403L, 624L, ..., -325092206L [6b9b92cc9debdb741d96ff4ef849aa33]
# example of backup/restore of RNG in functions
f <- function(){
orng <- RNGseed()
on.exit(RNGseed(orng))
RNGkind('Marsaglia')
runif(10)
}
sample(NA)
## [1] NA
s <- .Random.seed
f()
## [1] 0.9466 0.6266 0.3897 0.3948 0.1071 0.7840 0.3224 0.2289 0.7145 0.5210
identical(s, .Random.seed)
## [1] TRUE
## Don't show:
stopifnot(identical(s, .Random.seed))
## End Don't show