我想知道如何将Rcpp IntegerVector转换为NumericVetortor以进行三次采样,而不用替换数字1到5。
seq_len输出一个IntegerVector,而样本样本仅取一个NumericVector

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadilloExtensions/sample.h>
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector follow_path(NumericMatrix X, NumericVector y) {
IntegerVector i = seq_len(5)*1.0;
NumericVector n = i; //how to convert i?
return sample(cols_int,3); //sample only takes n input
}

最佳答案

您在这里出错了,或者也许我严重误解了这个问题。

首先,sample()确实接受整数向量,实际上它是模板化的。

其次,您根本没有使用参数。

这是修复的版本:

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadilloExtensions/sample.h>
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector sampleDemo(IntegerVector iv) {   // removed unused arguments
  IntegerVector is = RcppArmadillo::sample<IntegerVector>(iv, 3, false);
  return is;
}

/*** R
set.seed(42)
sampleDemo(c(42L, 7L, 23L, 1007L))
*/

这是它的输出:
R> sourceCpp("/tmp/soren.cpp")

R> set.seed(42)

R> sampleDemo(c(42L, 7L, 23L, 1007L))
[1] 1007   23   42
R>

编辑:当我写这篇文章的时候,你回答了自己...

关于Rcpp如何将IntegerVector转换为NumericVector,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30425334/

10-12 17:09