The aim of this function is to record, manipulate and restore a random state.
Value
a list with various infos about the random state after function execution, as well as a function to restore the previous state before the function execution.
Details
This function is intended for two (not mutually exclusive) tasks:
a) record the current random state.
b) change the current random state in a way that the previous state can be restored.
Examples
set.seed(13)
runif(1)
#> [1] 0.7103224
# testing the function in standard settings
currentSeed = .Random.seed
x = getRandomState(123)
runif(1)
#> [1] 0.2875775
x$restoreCurrent()
all(.Random.seed == currentSeed)
#> [1] TRUE
# if no seed was set in env, this will also be restored
rm(.Random.seed) # now, there is no random seed
#> Warning: object '.Random.seed' not found
x = getRandomState(123)
exists(".Random.seed") # TRUE
#> [1] TRUE
runif(1)
#> [1] 0.2875775
x$restoreCurrent()
exists(".Random.seed") # False
#> [1] TRUE
runif(1) # re-create a seed
#> [1] 0.2461373
# with seed = false
currentSeed = .Random.seed
x = getRandomState(FALSE)
runif(1)
#> [1] 0.3896344
x$restoreCurrent()
#> NULL
all(.Random.seed == currentSeed)
#> [1] FALSE
# with seed = NULL
currentSeed = .Random.seed
x = getRandomState(NULL)
runif(1)
#> [1] 0.09138367
x$restoreCurrent()
all(.Random.seed == currentSeed)
#> [1] TRUE