3

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! 

1 Answer 1

3

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

Pleasure, and welcome to StackOverflow. It is common here to a) 'upvote' an answer by clicking on the up-arrow, and b) 'accept' an answer (one has asked) by clicking on the tickmark you see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.