Rcpp Resets RNG State

My question is the continuation 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 its former state from C ++. For example, I would like the following code to create a matrix in which each column contains the same implementations 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 that does not work. In R, I can get the result in rows 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 greatly appreciated!

+5
source share
1 answer

This may not work (easy). There is some language in Writing R Extension that says that you cannot set seed from a level C API.

Now you can fool:

  • Init RNG of R
  • RNGScope some work, make sure it is completed by RNGScope , because our code is all the same.
  • Now trick and use Rcpp::Function() to call set.seed() .
  • Consider returning to step 2 or completing.
+3
source

All Articles