[Rcpp-devel] Call R function (bbonit at tin.it)
Douglas Bates
bates at stat.wisc.edu
Wed Jun 20 18:42:00 CEST 2012
On Wed, Jun 20, 2012 at 11:22 AM, Silkworth,David J.
<SILKWODJ at airproducts.com> wrote:
> 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.
There is an Rcpp::LogicalVector (R uses the name logical instead of
boolean) or you can just call Rcpp::wrap on a bool value, as shown in
the code I posted. The point is that, when passed back to R, the
elements in an Rcpp::LogicalVector are displayed as TRUE and FALSE.
An alternative is
return ::Rf_ScalarLogical(u);
which is a short-cut for creating an R logical vector of length 1
> 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.
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
More information about the Rcpp-devel
mailing list