Rcpp How to Convert IntegerVector to NumericVector

I was wondering how to convert Rcpp IntegerVector to NumericVetortor to try three times without replacing the numbers 1 through 5. seq_len outputs IntegerVector, and the sample pattern accepts only a numeric vector

// [[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 } 
+5
source share
2 answers

Something is wrong with you, or maybe I completely misunderstand the question.

First, sample() accepts whole vectors, in fact it is a pattern.

Secondly, you did not use your arguments at all.

Here is the edited 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 his conclusion:

 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 yourself answered ...

+6
source

I found out from http://adv-r.had.co.nz/Rcpp.html#rcpp-classes for use

 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); } 
+4
source

All Articles