Rcpp将RNG状态设置为先前状态

Pie*_*cob 5 r rcpp

我的问题是对http://rcpp-devel.r-forge.r-project.narkive.com/qJMEsvOK/setting-the-r-random-seed-from-rcpp的后续跟进.

我希望能够在C++中将RNG状态设置为以前的状态.例如,我希望以下代码生成一个矩阵,其中每列包含相同的Gamma随机变量实现.

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])
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用.在R中,我可以通过诸如的行来实现结果

.Random.seed <- x # reset the state to x
x <- .Random.seed # store the current state
Run Code Online (Sandbox Code Playgroud)

我错过了一些明显的东西吗 任何帮助将非常感激!

Dir*_*tel 3

这可能行不通(容易)——Writing R Extension 中有一些语言指出您无法从 C 级 API 设置种子。

现在,你可以作弊:

  1. 从 R 初始化 RNG
  2. 做一些工作,确保它RNGScope像我们的代码一样被包裹起来。
  3. 现在作弊并使用Rcpp::Function()来调用set.seed().
  4. 考虑是返回步骤 2 还是结束。