'setting seed locally (not globally) in R

I'd like to set seeds in R only locally (inside functions), but it seems that R sets seeds not only locally, but also globally. Here's a simple example of what I'm trying (not) to do.

myfunction <- function () {
  set.seed(2)
}

# now, whenever I run the two commands below I'll get the same answer
myfunction()
runif(1)

So, my questions are: why does R set the seed globally and not only inside my function? And how I can make R to set the seed only inside my function?



Solution 1:[1]

Using @Romain Francois's answer, generalize as function:

withRandom <- function(expr, seed = 1) {
    old <- .Random.seed
    on.exit({.Random.seed <<- old})
    set.seed(seed)
    expr
}

Usage:

runif(2)
withRandom(seed = 2, {
    runif(1)
    runif(1)
})
runif(2)
withRandom(seed = 2, runif(2))
runif(2)

output:

> runif(2)
[1] 0.5776099 0.6309793
> withRandom(seed = 2, {
+     runif(1)
+     runif(1)
+ })
[1] 0.702374
> runif(2)
[1] 0.5120159 0.5050239
> withRandom(seed = 2, runif(2))
[1] 0.1848823 0.7023740
> runif(2)
[1] 0.5340354 0.5572494

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1