Rcpp 将 RNG 状态设置为以前的状态

标签 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

我是否遗漏了一些明显的东西?任何帮助将不胜感激!

最佳答案

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

现在,你可以作弊:

  1. 从 R 初始化 RNG
  2. 做一些工作,确保它像我们的代码一样被 RNGScope 包装。
  3. 现在作弊并使用 Rcpp::Function() 调用 set.seed()
  4. 考虑是否返回第 2 步或完成。

关于Rcpp 将 RNG 状态设置为以前的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30466462/

相关文章:

c++ - 从 std::vector 到 adept::avector

xcode - OS X Mavericks 上的 RcppArmadillo 编译错误

c++ - Rcpp:使用 double 类型的浮点异常

r - 使用 Rcpp 的 R 上的柠檬图库

r - 为什么我们在 RcppArmadillo 上同时使用 "include"和 "depends"?

r - 将 MASS::fitdistr 按一个因子应用于多个数据

r - 使用 R 中一列中存在的值向量扩展 data.frame

r - 如何向量化模数?

r - R 中的时区问题,我想使用 UTC+0100,即使在夏天,尽管 CET 自动切换到 CEST

r - 如何在r中使用Predict.lm来逆转回归