setting seed locally (not globally) in R

后端 未结 2 415
灰色年华
灰色年华 2020-12-14 17:14

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

相关标签:
2条回答
  • 2020-12-14 17:37

    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
    
    
    0 讨论(0)
  • 2020-12-14 17:48

    Something like this does it for me:

    myfunction <- function () {
      old <- .Random.seed
      set.seed(2)
      res <- runif(1)
      .Random.seed <<- old
      res
    }
    

    Or perhaps more elegantly:

    myfunction <- function () {
      old <- .Random.seed
      on.exit( { .Random.seed <<- old } )
      set.seed(2)
      runif(1)
    }
    

    For example:

    > myfunction()
    [1] 0.1848823
    > runif(1)
    [1] 0.3472722
    > myfunction()
    [1] 0.1848823
    > runif(1)
    [1] 0.4887732
    
    0 讨论(0)
提交回复
热议问题