Pierre Jacob
Pierre Jacob

Reputation: 51

Rcpp set the RNG state to a former state

My question is a follow-up of http://rcpp-devel.r-forge.r-project.narkive.com/qJMEsvOK/setting-the-r-random-seed-from-rcpp.

I want to be able to set the RNG state to a former state from within C++. For example, I would like the following code to produce a matrix where each column contains the same realizations of Gamma random variables.

cppFunction('NumericMatrix rgamma_reset_seed(int n, double shape, double rate){
            RNGScope rngscope;
            Environment g = Environment::global_env();
            Environment::Binding RandomSeed = g[".Random.seed"];
            IntegerVector someVariable = RandomSeed;
            NumericMatrix results(n, 2);
            results(_,0) = rgamma(n, shape, 1/rate);
            RandomSeed = someVariable;
            results(_,1) = rgamma(n, shape, 1/rate);
            return results;  
}')
m <- rgamma_reset_seed(1000, 1.2, 0.8)
par(mfrow = c(2, 1))
plot(m[,1])
plot(m[,2])

But it does not seem to work. In R, I can achieve the result by lines such as

.Random.seed <- x # reset the state to x
x <- .Random.seed # store the current state

Am I missing something obvious? Any help would be much appreciated!

Upvotes: 5

Views: 178

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368509

This may not work (easily) -- there is some language in Writing R Extension which states that you cannot set the seed from the C level API.

Now, you could cheat:

  1. Init RNG from R
  2. Do some work, make sure this is wrapped by RNGScope as our code does anyway.
  3. Now cheat and use Rcpp::Function() to invoke set.seed().
  4. Consider whether to go back to step 2 or to finish.

Upvotes: 3

Related Questions