Reputation: 51
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
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:
RNGScope
as our code does anyway.Rcpp::Function()
to invoke set.seed()
.Upvotes: 3