将Rcpp NumericVector随机分为2

将Rcpp NumericVector随机分为2,r,rcpp,R,Rcpp,我试着把一个向量分成两个大小相等的向量。通常在R中,这将使用 indices = sample(1:length(x), length(x)/2) a = x[indices] b = x[-indices] 在Rcpp中,我可以从RcppArmadillo复制示例函数。然而,Rcpp中的子集似乎不能处理像x[-index]这样的事情。您可以使用RcppArmadillo::sample对所有索引进行洗牌,然后将前半部分提取到一个向量,将后半部分提取到另一个向量: // file.cpp //

我试着把一个向量分成两个大小相等的向量。通常在R中,这将使用

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

在Rcpp中,我可以从RcppArmadillo复制示例函数。然而,Rcpp中的子集似乎不能处理像
x[-index]

这样的事情。您可以使用
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;
}

您可以使用
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;
}