Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an integer parameter in Rcpp

Tags:

c++

r

rcpp

Is it possible to convert an integer SEXP parameter to an integer directly without first converting it to an integer vector?

Example:

#include <Rcpp.h>

SEXP f(SEXP n)
{
    Rcpp::IntegerVector n_vec(n);
    int n1 = n_vec[0];
    ...
    return R_NilValue;
}
like image 932
August Karlstrom Avatar asked May 15 '13 08:05

August Karlstrom


1 Answers

Of course -- the as<>() converter does this.

It can be called explicitly (which you need here), is sometimes called implicitly by the compiler, or even inserted by code generation helpers like this:

R> cppFunction('int twiceTheValue(int a) { return 2*a; }')
R> twiceTheValue(21)
[1] 42
R> 

If you call cppFunction() (and the related functions from Rcpp attributes, or the inline package) with the verbose=TRUE argument, you see the generated code.

Here, I get

#include <Rcpp.h>

RcppExport SEXP sourceCpp_47500_twiceTheValue(SEXP aSEXP) {
BEGIN_RCPP
    Rcpp::RNGScope __rngScope;
    int a = Rcpp::as<int >(aSEXP);
    int __result = twiceTheValue(a);
    return Rcpp::wrap(__result);
END_RCPP
}

and our documentation explains what the BEGIN_RCPP, END_RCPP macros do, why the RNGScope object is there -- and you see the as<>() and wrap() you needed.

like image 157
Dirk Eddelbuettel Avatar answered Oct 17 '22 00:10

Dirk Eddelbuettel