Rcpp如何将IntegerVector转换为NumericVector

10

我想知道如何将Rcpp中的IntegerVector转换为NumericVector,以便对从1到5的数字进行三次不重复抽样。seq_len输出一个IntegerVector,而sample函数只接受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
}

为什么我问这个问题被踩了? - Soren Havelund Welling
2个回答

11

你的一些地方有误,或者我可能严重误解了问题。

首先,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> 

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


9
我从http://adv-r.had.co.nz/Rcpp.html#rcpp-classes学到如何使用Rcpp类。
NumericVector cols_num = as<NumericVector>(someIntegerVector)

.

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

// [[Rcpp::export]]
NumericVector follow_path(NumericMatrix X, IntegerVector y) {
 IntegerVector cols_int = seq_len(X.ncol());
 NumericVector cols_num = as<NumericVector>(cols_int);
 return sample(cols_num,3,false);
}

1
你仍在不必要地进行类型转换。如果你想对整数向量进行采样,请去采样整数向量——请参考我的答案。 - Dirk Eddelbuettel
1
如果我的回答有帮助,请考虑“接受”(点击勾号)和/或“点赞”(点击向上三角形),这两个操作在 Stack Overflow 上很常见。 - Dirk Eddelbuettel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接