我试着把一个向量分成两个大小相等的较小的向量。通常在R中,这将使用以下命令完成
indices = sample(1:length(x), length(x)/2)
a = x[indices]
b = x[-indices]在Rcpp中,我可以复制RcppArmadillo中的示例函数。然而,看起来Rcpp中的子集并不能处理像x[-indices]这样的事情。
发布于 2015-06-27 13:08:10
您可以使用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 17https://stackoverflow.com/questions/31084553
复制相似问题