# Restore the seed
.Random.seed<-oldseed# Get the same random numbers as before, after saving the seed
runif(3)#> [1] 0.7973768 0.2278427 0.5189830

If no random number generator has been used in your R session, the variable .Random.seed will not exist. If you cannot be certain that an RNG has been used before attempting to save, the seed, you should check for it before saving and restoring:

oldseed<-NULLif(exists(".Random.seed"))oldseed<-.Random.seed# Do some other stuff with RNG here, such as:
# runif(30)
# ...
if(!is.null(oldseed)).Random.seed<-oldseed

Saving and restoring the state of the RNG in functions

If you attempt to restore the state of the random number generator within a function by using .Random.seed <- x, it will not work, because this operation changes a local variable named .Random.seed, instead of the variable in the global envrionment.

Here are two examples. What these functions are supposed to do is generate some random numbers, while leaving the state of the RNG unchanged.