[Rcpp-devel] Call R function (bbonit at tin.it)

Silkworth,David J. SILKWODJ at airproducts.com
Wed Jun 20 18:22:36 CEST 2012


I am not going to ask why to do this, but here is a way how.

I added your R function into the mypackage skeleton from RcppPackage

R_user_F<-function (par) {
y<-par[1]
x<-par[2]
return(dnorm(x)*dnorm(y))
}

I prefer to use the explicit return function for clarity.

Now I install the package after a binary build.  It has become a part of R.

The code you wish that calls this function is as follows:

require(mypackage)
require(inline)

src <- '
Rcpp::NumericVector par=(arg1);
Rcpp::NumericVector par1(2);
Rcpp::NumericVector par2(2);
Rcpp::NumericVector f1(1);
Rcpp::NumericVector f2(1);
Rcpp::NumericVector outval(1);
double a=2;
double b=3;
par1=par*b;
par2=par*a;
Environment mypackage("package:mypackage");
Function R_userf = mypackage["R_user_F"];
f1=R_userf(par1);
f2=R_userf(par2);
bool u = (Rf_runif(0.0,1.0) <= f2[0]-f1[0]  );
outval[0]=u;
return(outval);
'

 RcppGibbs  <- cxxfunction(signature(arg1 = "numeric"),
 src, plugin = "Rcpp")

I had to assume that you wished to return the Boolean result.  There is no Rcpp::BooleanVector, so we have to use the knowledge that a Boolean in C++ is just an integer 0 for false and 1 for true.

You will have to run a quick test on the return value to get the Boolean in R.

Notice that you have to dimension your Rcpp::NumericVector on declaration.
You must address the value you wish when making calculations so f2-f1, becomes f2[0]-f1[0] in this case.



More information about the Rcpp-devel mailing list