Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling R function from C++, using Rcpp

Tags:

r

inline

rcpp

I am teaching myself Rcpp and notice that Rcpp sugar does not have sample function. So I decided to call sample function in base library from C++. I have two questions:

1. Regarding the type of the arguments prob, am I supposed to use NumericVector? Is it legall to use vector type?

2. Regarding the type of the output, am I supposed to use IntegerVector? Is it legall to use NumericVector type?

It seems all these types are fine (See the code below) but I would like to know which type is better to use.

<!-- language-all: lang-html -->
library(inline)
library(Rcpp)

src1 <- '
   RNGScope scope;

  NumericVector thenum(1),myprob(3);

  myprob[0]=0.1;
  myprob[1]=0.5;
  myprob[2]=0.4;

  Environment base("package:base");
  Function sample = base["sample"];

  thenum = sample(3,Named("size",1),Named("prob",myprob));

  return wrap(thenum);
'


src2 <- '
  RNGScope scope;

  IntegerVector theint(1);
  vector<double> myprob(3);
    myprob[0]=0.1;
  myprob[1]=0.5;
  myprob[2]=0.4;
  Environment base("package:base");
  Function sample = base["sample"];

  theint = sample(3,Named("size",1),Named("prob",myprob));

  return wrap(theint);
'


fun1 <- cxxfunction(signature(),body=src1,plugin="Rcpp")
fun2 <- cxxfunction(signature(),body=src2,include='using namespace std;',plugin="Rcpp")

fun1() ## work!
fun2() ## oh this works too! 
like image 459
FairyOnIce Avatar asked Jul 12 '26 06:07

FairyOnIce


1 Answers

Because you are calling sample() from R, both integer and numeric works as they do in R itself:

R> set.seed(42); sample(seq(1L, 5L), 5, replace=TRUE)
[1] 5 5 2 5 4
R> set.seed(42); sample(seq(1.0, 5.0), 5, replace=TRUE)
[1] 5 5 2 5 4
R> 
like image 78
Dirk Eddelbuettel Avatar answered Jul 17 '26 22:07

Dirk Eddelbuettel