[英]Randomly divide Rcpp NumericVector into 2
I am trying to divide a vector into 2 smaller vectors of equal size. 我正在尝试将一个向量分成相等大小的2个较小的向量。 Normally in R this would be done using
通常在R中,这可以使用
indices = sample(1:length(x), length(x)/2)
a = x[indices]
b = x[-indices]
In Rcpp I can replicate the sample function from RcppArmadillo. 在Rcpp中,我可以从RcppArmadillo复制示例函数。 However, it seems that subsetting in Rcpp does not handle things like
x[-indices]
. 但是,似乎Rcpp中的子集无法处理
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: 您可以使用
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;
}
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.