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

时间:2015-05-26 18:44:45

标签: 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])

但它似乎不起作用。在R中,我可以通过诸如

之类的行来实现结果
.Random.seed <- x # reset the state to x
x <- .Random.seed # store the current state

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

1 个答案:

答案 0 :(得分:3)

这可能不起作用(很容易) - Writing R Extension中有一些语言表明你不能从C级API设置种子。

现在,你可以作弊:

  1. 来自R的初始RNG
  2. 做一些工作,确保它由RNGScope包裹,因为我们的代码仍然如此。
  3. 现在作弊并使用Rcpp::Function()来调用set.seed()
  4. 考虑是回到第2步还是完成。