[Rcpp-devel] Idiom for accessing scalars

Douglas Bates bates at stat.wisc.edu
Fri Jan 6 18:49:17 CET 2012


2012/1/4 Romain François <romain at r-enthusiasts.com>:
> Le 04/01/12 14:29, Hadley Wickham a écrit :
>
>> Hi all,
>>
>> I'm still just getting my feet wet in Rcpp, so please excuse the
>> naivety of my question, but is this the appropriate idiom for treating
>> an input as a C++ scalar?
>>
>> f<- cxxfunction(signature(x = "integer"), plugin = "Rcpp", '
>>   Rcpp::IntegerVector x1(x);
>>   int x2 = x1[0];
>>
>>   return(Rcpp::NumericVector(x2));
>> ')
>>
>> i.e. is there any way I can turn x in x2 more succinctly?  (This
>> function is just for illustrative purposes - I'm trying to do
>> something at least a little more complicated)
>>
>> Thanks!
>>
>> Hadley
>
> Yep,
>
> We have "as" for this, and wrap for the other way around:
>
>
> f<- cxxfunction(signature(x = "integer"), plugin = "Rcpp", '
>  int x2 = as<int>(x) ;
>
>  return wrap(x2) ;
> ')

As I mentioned in another thread, I prefer the idiom

int n2 = ::Rf_asInteger(n);

because asInteger is part of the R API (in Rcpp it must be called as
Rf_asInteger - the :: is a hint to the compiler that it will be found
in the global namespace).  Functions like asInteger and asReal are
used in thousands of places in the base R code and have been optimized
to death as well as being as general as they can possibly be.


More information about the Rcpp-devel mailing list