Using an integer parameter in Rcpp

Is it possible to convert an integer parameter SEXP 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; } 
+4
source share
1 answer

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

It can be called explicitly (which you need here), sometimes called an implicit compiler, or even inserted using code generation helpers as follows:

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

If you call cppFunction() (and related functions from the Rcpp attributes or 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 there is an RNGScope object, and you see as<>() and wrap() that you need.

+6
source

Source: https://habr.com/ru/post/1480885/


All Articles