Can I get.seed() somehow?

后端 未结 4 1438
不知归路
不知归路 2020-11-30 09:55

In reference to the statement set.seed(), can I get the seed instead after running some code if I didn\'t set it explicitly?

I\'ve been re-running some

相关标签:
4条回答
  • 2020-11-30 10:06

    If you didn't keep the seed, there's no general way to "roll back" the random number generator to a previous state after you've observed a random draw. Going forward, what you may want to do is save the value of .Random.seed along with the results of your computations. Something like this.

    x <- .Random.seed
    result <- <your code goes here>
    attr(result, "seed") <- x
    

    Then you can reset the PRNG as follows; result2 should be the same as result.

    .Random.seed <- attr(result, "seed")
    result2 <- <your code goes here>
    
    0 讨论(0)
  • 2020-11-30 10:08

    To add to the answer mpettis gave, if you don't want to re-execute the script manually--generating new random seeds each iteration--you could do something like this:

    # generate vector of seeds
    eff_seeds <- sample(1:2^15, runs)
    
    # perform 'runs' number of executions of your code
    for(i in 1:runs) {
        print(sprintf("Seed for this run: %s", eff_seeds[i]))
        set.seed(eff_seeds[i])
    
        # your code here
        # don't forget to save your outputs somehow
    }
    

    Where the variable 'runs' is a positive integer indicating the number of times you want to run your code.

    This way you can generate a lot of output rapidly and have individual seeds for each iteration for reproducibility.

    0 讨论(0)
  • 2020-11-30 10:20
    > rnorm(5)
    [1] -0.17220331 -0.31506128 -0.35264299  0.07259645 -0.15518961
    > Seed<-.Random.seed
    > rnorm(5)
    [1] -0.64965000  0.04787513 -0.14967549  0.12026774 -0.10934254
    > set.seed(1234)
    > rnorm(5)
    [1] -1.2070657  0.2774292  1.0844412 -2.3456977  0.4291247
    > .Random.seed<-Seed
    > rnorm(5)
    [1] -0.64965000  0.04787513 -0.14967549  0.12026774 -0.10934254
    
    0 讨论(0)
  • 2020-11-30 10:23

    Hong's answer above is robust. For quick and dirty solutions, where I just re-execute a whole script until I get interesting behavior, I randomly pick an integer, print it out, then use that as a seed. If my particular run has interesting behavior, I note that seed:

    eff_seed <- sample(1:2^15, 1)
    print(sprintf("Seed for session: %s", eff_seed))
    set.seed(eff_seed)
    
    0 讨论(0)
提交回复
热议问题