简体   繁体   English

Rcpp如何将IntegerVector转换为NumericVector

[英]Rcpp How to convert IntegerVector to NumericVector

I was wondering how to convert Rcpp IntegerVector to NumericVetortor to sample three times without replacement of the numbers 1 to 5. seq_len outputs an IntegerVector and sample sample only takes an NumericVector 我想知道如何将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
}

You are having a few things wrong here, or maybe I grossly misunderstand the question. 你在这里犯了一些错误,或者我可能误解了这个问题。

First off, sample() does take integer vectors, in fact it is templated. 首先, sample() 确实采用整数向量,实际上它是模板化的。

Second, you were not using your arguments at all. 其次,你根本没有使用你的论据。

Here is a repaired version: 这是一个修复版本:

// [[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))
*/

and this is its output: 这是它的输出:

R> sourceCpp("/tmp/soren.cpp")

R> set.seed(42)

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

Edit: And while I wrote this, you answered yourself... 编辑:当我写这篇文章时,你自己回答了......

I learned from http://adv-r.had.co.nz/Rcpp.html#rcpp-classes to use 我从http://adv-r.had.co.nz/Rcpp.html#rcpp-classes学习使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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