This is a scoping issue. I think what you want in your example is

test <-  function(runs, seed) {
  # this is a local copy of ".Random.seed"
  .Random.seed <- seed
  # need to make a global copy
  assign(".Random.seed", .Random.seed, 1)
  for (i in 1:runs) {
    print(i)
    print(runif(1,0,1))
    print(.Random.seed)
  }
  return(.Random.seed)
}

RNGkind(kind="Marsaglia-Multicarry")
set.seed(20391)
seed1 <- .Random.seed
seed1
test(2, seed1)
test(2, seed1)


Hope this helps,


-sundar

Ann Hess wrote:
I am writing a function for the purposes of a simulation.  Due to memory
problems, the function sometimes crashes.  In order to get around this
problem, I would like to include to be able to save the "last" seed, so I
can pick up with the next run of the simulation after a "crash".  I am
having trouble understanding what is going on with .Random.seed!

For each run of the following function, a random uniform and the current
.Random.seed should be printed:

test<-function(runs,seed){
   .Random.seed<-seed
   for (i in 1:runs) {
print(i)
print(runif(1,0,1))
print(.Random.seed)}
   return(.Random.seed}

Consider the following input/output:

RNGkind(kind="Marsaglia-Multicarry")
set.seed(20391)
seed1<-.Random.seed
seed1

[1] 401 -1607331462 -462081869


test(2,seed1)

[1] 1 [1] 0.4188851 [1] 401 -1607331462 -462081869 [1] 2 [1] 0.7713649 [1] 401 -1607331462 -462081869 [1] 401 -1607331462 -462081869

seed1

[1] 401 -1607331462 -462081869


test(2,seed1)

[1] 1 [1] 0.7293294 [1] 401 -1607331462 -462081869 [1] 2 [1] 0.8266798 [1] 401 -1607331462 -462081869 [1] 401 -1607331462 -462081869


The output from each call of the function seems to suggest that .Random.seed is not changing (although different random uniforms are generated each time). The second call of the function doesn't match the first call even though the same "seed" is used.

Can anyone explain what is happening here?  My goal is to save the "last"
seed so that I can use it to generate the next run of a simulation (after
a crash).

Thanks in advance!

______________________________________________
[EMAIL PROTECTED] mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help

______________________________________________ [EMAIL PROTECTED] mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help

Reply via email to