简体   繁体   中英

Randomly divide Rcpp NumericVector into 2

I am trying to divide a vector into 2 smaller vectors of equal size. Normally in R this would be done using

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

In Rcpp I can replicate the sample function from RcppArmadillo. However, it seems that subsetting in Rcpp does not handle things like x[-indices] .

You could shuffle all indices with RcppArmadillo::sample and then extract the first half to one vector and the second half to the other vector:

// 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;
}

This returns your split up list:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM