在 Rcpp 中用随机生成的值填充向量的一部分

Fill a part of a vector with randomly generated values in Rcpp

我正在尝试在 Rcpp 中编写顺序 Monte Carlo 函数,但遇到以下问题:

我通过以下方式创建了一个向量:

  NumericVector R_t(Part*Ttau);

我只想填充向量的部分块。它应该是这样的:

for (int i=0;i<Part;i++){
        R_t[i]=runif(1,0,2);
}

我想要第二次

for (int i=Part+1;i<2*Part;i++){
            R_t[i]=runif(1,0,2);
}

不过好像不行。我可以在每次迭代中用新值替换旧值,但每次迭代都需要旧值。当我尝试编译时,出现以下错误:

cannot convert 'Rcpp::NUmericVector {aka Rcpp::Vector<14, Rcpp::PrserveStorage>}' to 'Rcpp::traits::storage_type<14>:: type {aka double}' in assignment

用具有 Part 和 Ttau 维度的二维矩阵替换向量会更容易吗?我想避免这最后一个选项。

很抱歉,如果这已经得到回答,但我没有找到与此接近的 rcpp

您正在尝试将长度为一的向量分配给需要 double 的位置,因此请使用 [0] 访问第一个元素:runif(1,0,2)[0]。但是,您也可以只用 Rcpp 糖结构替换循环,以避免一次重复生成一个随机值:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector fill_vector(R_xlen_t n, R_xlen_t m) {
    Rcpp::NumericVector res(n);
    for (R_xlen_t i = 0; i < m; i++) {
        res[i] = Rcpp::runif(1, 0, 2)[0];
    }
    return res;
}

// [[Rcpp::export]]
Rcpp::NumericVector fill_vector2(R_xlen_t n, R_xlen_t m) {
    Rcpp::NumericVector res(n);
    res[Rcpp::seq(0, m - 1)] = Rcpp::runif(m, 0, 2);
    return res;
}

/***R

set.seed(123)
fill_vector(7, 4)
#[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000

set.seed(123)
fill_vector2(7, 4)
#[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000

set.seed(123)
c(runif(4, 0, 2), rep(0, 3))
#[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000

*/

关于 RNG,您有两种选择:

  1. 使用Rcpp sugar通过Rcpp::runif(n,a,b)匹配R中的runif(n,a,b)(returnsNumericVector
  2. 通过每次从 R::runif(a,b)
  3. 绘制来创建自己的循环来模仿 runif(n,a,b)

@nrussell 演示了如何通过 Rcpp::runif(n,a,b)[0] 对向量进行子集化来使用 1,但省略了方法 2。

下面是方法 2 的执行方法:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector draw_vector(int n, int m) {
  Rcpp::NumericVector res(n);
  for (int i = 0; i < m; i++) {
    res[i] = R::runif(0.0, 2.0); // Draw a single element that is a double
  }
  return res;
}

/***R
set.seed(123)
draw_vector(7, 4)
*/

这给出:

[1] 0.5751550 1.5766103 0.8179538 1.7660348 0.0000000 0.0000000 0.0000000