dimanche 25 décembre 2016

Reproducible Random Values in Vector

I need to generate a random number corresponding to each value in an index, where it needs to be reproducible for each index value, regardless of how many indexes are given:

As an example, I might provide the indexes 1 to 10, and then in a different time, call the indexes for 5 to 10, and they both need to be the same for the values 5 to 10. Setting a global seed will not do this, it will only keep same for the nth item in the random call by position in the vector.

What I have so far is this:

f = function(ix,seed=1){
  sapply(ix,function(x){
    set.seed(seed + x)
    runif(1)
  })
}
identical(f(1:10)[5:10],f(5:10)) #TRUE

I was wondering if there is a more efficient way of achieving the above, without setting the seed explicitly for each index, as an offset to global seed.




Aucun commentaire:

Enregistrer un commentaire