【问题标题】:Randomly divide Rcpp NumericVector into 2将 Rcpp NumericVector 随机分为 2
【发布时间】:2015-06-27 02:29:48
【问题描述】:

我正在尝试将一个向量分成 2 个大小相等的较小向量。通常在 R 中,这将使用

indices = sample(1:length(x), length(x)/2)
a = x[indices]
b = x[-indices]

在 Rcpp 中,我可以复制 RcppArmadillo 中的示例函数。但是,Rcpp 中的子集化似乎无法处理 x[-indices] 之类的事情。

【问题讨论】:

    标签: r rcpp


    【解决方案1】:

    您可以使用RcppArmadillo::sample 打乱所有索引,然后将前半部分提取到一个向量,将后半部分提取到另一个向量:

    // file.cpp
    // [[Rcpp::depends(RcppArmadillo)]]
    
    #include <RcppArmadilloExtensions/sample.h>
    
    using namespace Rcpp ;
    
    // [[Rcpp::export]]
    List fxn(NumericVector x) {
      const int n = x.size();
      const int n2 = x.size()/2;
    
      // Randomly order indices
      NumericVector v(n);
      std::iota(v.begin(), v.end(), 0);
      NumericVector indices = RcppArmadillo::sample(v, v.size(), false);
    
      // Split up vectors
      NumericVector a(n2);
      NumericVector b(n - n2);
      for (int i=0; i < n2; ++i) a[i] = x[indices[i]];
      for (int i=n2; i < n; ++i) b[i-n2] = x[indices[i]];
    
      // Return as a list
      List ret;
      ret["a"] = a;
      ret["b"] = b;
      return ret;
    }
    

    这将返回您的拆分列表:

    library(Rcpp)
    sourceCpp("file.cpp")
    fxn(10:20)
    # $a
    # [1] 12 10 20 18 19
    # 
    # $b
    # [1] 11 16 13 14 15 17
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2023-03-04
      • 2019-12-19
      相关资源
      最近更新 更多