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::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.
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With