[Rcpp-devel] Call R function

Douglas Bates bates at stat.wisc.edu
Wed Jun 20 15:57:17 CEST 2012

On Wed, Jun 20, 2012 at 12:52 AM, bbonit at tin.it <bbonit at tin.it> wrote:
> Hello i would like to compute the following code ;
> Where R_user_F is a R function  (i could write this function directly inin
> line but is only for example because i want to call an R function more
> complex):
> so when compile appear this error  message:  error:
> "cannot convert 'Rcpp::sugar::Comparator_With_One_Value<14,
> Rcpp::sugar::greater_or_equal<14>, true,
> Rcpp::sugar::Minus_Vector_Vector<14, true, Rcpp::Vector<14>, true,
> Rcpp::Vector<14> > >' to 'bool' in initialization."
>  I can do for solve this problem? Thank You.
> The code:
> R_user_F<-function (par) {
> y<-par[1]
> x<-par[2]
> dnorm(x)*dnorm(y)
> }
> require(inline)
> code <- '
> NumericVector f1;
> NumericVector f2;
> NumericVector par1;
> NumericVector par2;
> NumericVector a=2;
> NumericVector b=3;
> NumericVector par =par;
> par1=par*b;
> par2=par*a;
> Function R_userf(fun);
> f1=R_userf(par1);
> f2=R_userf(par2);
> bool u = (Rf_runif(0.0,1.0) <= f2-f1  );
> '
> RcppGibbs <- cxxfunction(signature( par ="NumericVector", fun="function"),
> code,
> include='#include <math.h>',
> plugin="Rcpp")<-function (par) {
> y<-par[1]
> x<-par[2]
> dnorm(x)*dnorm(y)
> }

I don't understand the last call.  In cxxfunction the signature
argument uses the names of R classes, not Rcpp classes, so the
specification should be par="numeric".  Also, the second assignment
(RcppGibbs <- cxxfunction(...) <- function(par)) would be an error
because you can't assign to the cxxfunction call.

The error message relates to the expression Rf_runif(0.0, 1.0) <= f1 -
f2 because Rf_unif(0.0, 1.0) returns a double and f1 - f2 is a
NumericVector.  You should use (f1-f2)[0] to convert to a double.

With regard to your code, you are writing C++ in a C style where you
declare all the variables then assign them.  That isn't the best
approach in C++ because default constructors can be expensive. I
always find it easier to use constructors in declarations rather than
declarations followed by assignment in C++.  If you use a declaration

NumericVector f1;

then later assign

f1 = R_userf(par1)

you end up creating a NumericVector of length 0 then creating another
NumericVector of length > 0 to overwrite it.

I would begin by assigning the values of the arguments to Rcpp
objects.  I'll post a revised version shortly.

More information about the Rcpp-devel mailing list