Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rcpp set the RNG state to a former state

Tags:

r

rcpp

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!

like image 248
Pierre Jacob Avatar asked Oct 19 '22 10:10

Pierre Jacob


1 Answers

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.
like image 61
Dirk Eddelbuettel Avatar answered Oct 22 '22 01:10

Dirk Eddelbuettel