Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rcpp How to convert IntegerVector to NumericVector

Tags:

r

rcpp

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
}
like image 282
Soren Havelund Welling Avatar asked May 24 '15 15:05

Soren Havelund Welling


2 Answers

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

like image 73
Dirk Eddelbuettel Avatar answered Nov 10 '22 22:11

Dirk Eddelbuettel


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);
}
like image 9
Soren Havelund Welling Avatar answered Nov 10 '22 22:11

Soren Havelund Welling