Learn R Programming

DHARMa (version 0.4.7)

getRandomState: Record and restore a random state

Description

The aim of this function is to record, manipulate and restore a random state.

Usage

getRandomState(seed = NULL)

Value

A list with various infos about the random state that after function execution, as well as a function to restore the previous state before the function execution.

Arguments

seed

seed argument to set.seed(), typically a number. Additional options: NULL = no seed is set, but return includes function for restoring random seed. F = function does nothing, i.e. neither seed is changed, nor does the returned function do anything.

Author

Florian Hartig

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

Run this code

set.seed(13)
runif(1)

# testing the function in standard settings
currentSeed = .Random.seed
x = getRandomState(123)
runif(1)
x$restoreCurrent()
all(.Random.seed == currentSeed)

# if no seed was set in env, this will also be restored

rm(.Random.seed) # now, there is no random seed
x = getRandomState(123)
exists(".Random.seed")  # TRUE
runif(1)
x$restoreCurrent()
exists(".Random.seed") # False
runif(1) # re-create a seed

# with seed = false 
currentSeed = .Random.seed
x = getRandomState(FALSE)
runif(1)
x$restoreCurrent()
all(.Random.seed == currentSeed)

# with seed = NULL 
currentSeed = .Random.seed
x = getRandomState(NULL)
runif(1)
x$restoreCurrent()
all(.Random.seed == currentSeed)

Run the code above in your browser using DataLab